サービスからメール送信 - javax.mail を使った日本語でのメールの送信(starttlsで認証付き)
メールの送信(認証あり)
- 昨日に引き続き、今度は認証あり(starttls)でメールを送信する手順を記載します
ライブラリの取得
- Javaのライブラリの管理は「Maven」を使っていることとして記載します
- ライブラリの指定は、dependencyに以下を追加
<dependency> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> <version>1.4.7</version> </dependency>
メール送信
- 以下のコードでメールを送信できます
import java.io.UnsupportedEncodingException; import java.util.Date; import java.util.Properties; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; public class MailWithAuth { /** SMTPのホスト */ public static final String HOST = "yor.smtp.host.name"; /** SMTPのポート */ public static final int PORT = 587; /** メール送信元のアドレス(システムの送信アドレス) */ public static final String FROM_ADDRESS = "notify@your.system.address"; /** メール送信元の名前(下のエンコードが日本語なので、日本語OK) */ public static final String FROM_NAME = "XXXサービスからのご連絡(送信専用)"; /** メールのエンコード(日本語) */ public static final String ENCODE = "ISO-2022-JP"; /** SMTPの認証ID */ public static final String SMTP_ID = "smtp user id"; /** SMTPの認証パスワード */ public static final String SMTP_PASSWORD = "smtp password"; public static void main(String[] args) throws Exception { MailWithAuth mail = new MailWithAuth(); mail.send(); } /** * メール送信 * @throws UnsupportedEncodingException * @throws MessagingException */ private void send() throws UnsupportedEncodingException, MessagingException { // 宛先のアドレス String to = "target@hogehoge.com"; // 宛先の名前 String toName = "宛先の名前"; // メールのタイトル String title = "XXXサービスからの○○○○のご連絡"; // メールの本文 String message = "xxx さん。平素XXXサービスをご利用いただきありがとうございます........"; // starttlsで、かつ認証ありのメールのセッション生成 Properties property = new Properties(); property.put("mail.smtp.host", HOST); property.put("mail.smtp.port", String.valueOf(PORT)); property.put("mail.smtp.socketFactory.port", String.valueOf(PORT)); property.put("mail.smtp.debug", "true"); property.put("mail.smtp.auth", "true"); property.put("mail.smtp.starttls.enable", "true"); property.put("mail.smtp.ssl.trust", HOST); Session session = Session.getInstance(property, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(SMTP_ID, SMTP_PASSWORD); } }); MimeMessage mimeMessage = new MimeMessage(session); InternetAddress toAddress = new InternetAddress(to, toName, ENCODE); mimeMessage.setRecipient(Message.RecipientType.TO, toAddress); InternetAddress fromAddress = new InternetAddress(FROM_ADDRESS, FROM_NAME, ENCODE); mimeMessage.setFrom(fromAddress); mimeMessage.setSubject(title, ENCODE); mimeMessage.setText(message, ENCODE); // 送信日付を指定 mimeMessage.setSentDate( new Date() ); Transport.send(mimeMessage); System.out.println("送信しました"); } }
以上です。