守破離でいこう! -Let's go with SyuHaRi!-

2007/03/16

JavaMailでAuth認証とOutbound Port25 Blocking(OP25B)対策

JavaからMailを送信するのに、javax.mailを使って送信していたのですが、社内のサーバ構成を変更しているうちに送信できなくなってしまった。

javax.mail.SendFailedException: Sending failed;
  nested exception is:
 class javax.mail.SendFailedException: Invalid Addresses;
  nested exception is:
 class javax.mail.SendFailedException: 553 sorry, that domain isn't in my list of allowed rcpthosts (#5.7.1)

 at javax.mail.Transport.send0(Transport.java:218)
 at javax.mail.Transport.send(Transport.java:80)
 at SendMail.sendMail(SendMail.java:42)
        ...

どうやら認証が必要なようです。
今までは同じホストでアプリケーションが稼動していたので問題なかったようです。

というわけで、Auth認証、そしてOutbound Port25 Blocking(OP25B)対策をして対処しました。

import java.util.Properties;
import java.util.Date;
import javax.mail.Session;
import javax.mail.Message;
import javax.mail.Transport;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.InternetAddress;
import javax.mail.Authenticator; 
import javax.mail.PasswordAuthentication; 

public class SendMail {
  public void sendMail(
    String sourceAdd, 
    String sourceName,
    String descAdd,
    String subject, String message,
    String type) {
    try {
      Properties props = System.getProperties();
      props.put("mail.smtp.host","mail.hoge.com");
      props.put("mail.smtp.port", "587");
      props.put("mail.smtp.auth", "true");
      Authenticator auth = new MyAuthenticator(); 
      Session session=Session.getDefaultInstance(props, auth);
      MimeMessage mimeMessage=new MimeMessage(session);
      mimeMessage.setFrom(new InternetAddress(sourceAdd, sourceName, "iso-2022-jp"));
      mimeMessage.setRecipients(Message.RecipientType.TO, descAdd);
      mimeMessage.setSubject(subject, "iso-2022-jp");
      mimeMessage.setText(message, "iso-2022-jp");
      mimeMessage.setHeader("Content-Type", type);
      mimeMessage.setSentDate(new Date());
      Transport.send(mimeMessage);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

class MyAuthenticator extends Authenticator {
  protected PasswordAuthentication getPasswordAuthentication() { 
    return new PasswordAuthentication("user" , "password"); 
  }
}

ラベル:

naoki 18:24 | 0 comments |
HaloScan: |