JavaからMail送信

2018年2月11日 - 未分類

itpManagerからお知らせメール機能で、メール送信する機能があります。汎用的なメール送信は、設定項目が多くて使いにくいので、gmailを対象に作成していました。しかし、gmailが、2段認証をしないと送信できなくされてしまい。これもまた、使いにくくなってしまいました。色々と調べた所、yahoo mailなら、面倒なく送信できることがわかりました。

package mail.send;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;

public class mailsend{

static String mailAccount=new String("Yahooアカウント");
static String mailID=new String(mailAccount+"@yahoo.co.jp");
static String mailPasswd=new String("パスワード");

 

public static void main(String[] args) {
try {
// SMTPサーバー設定
Properties props = System.getProperties();
props.setProperty("mail.debug", "true");
props.setProperty( "mail.smtp.port", "587");
props.setProperty("mail.smtp.socketFactory.port", "587");
props.put( "mail.smtp.host", "smtp.mail.yahoo.co.jp" );
props.setProperty("mail.smtp.auth", "true");
Session session = Session.getInstance(props, new Authenticator(){
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication( mailAccount, mailPasswd);
}
});

MimeMessage mimeMessage=new MimeMessage( session );
// 送信元メールアドレスと送信者名を指定
mimeMessage.setFrom( new InternetAddress( mailID, "itplanter", "ISO-2022-JP" ) );
// 送信先メールアドレスを指定
mimeMessage.setRecipients( Message.RecipientType.TO, mailID );
// メールのタイトルを指定
mimeMessage.setSubject("アイティプランターからのお知らせ", "ISO-2022-JP" );
// メールの内容を指定
mimeMessage.setText( "こんにちは\n", "ISO-2022-JP" );
// メールの形式を指定
mimeMessage.setHeader( "Content-Type", "text/html" );
// 送信日付を指定
mimeMessage.setSentDate( new Date() );
// 送信します
Transport.send( mimeMessage );
} catch (Exception e) {
e.printStackTrace();
}
}

}
Translate »