Java プログラムメモ


トップ

SMTP認証でメール送信

基本的なメール送信を行う場合はメール送信を参考にして下さい。 SMTP 認証を行う場合の例を書きます。

テキストメール送信例

import java.util.*; import javax.mail.*; import javax.mail.internet.*; public class MailTest { private String charset; private Session session; private String smtpHost; public MailTest(String smtpHost, String charset) { if (smtpHost == null) { throw new NullPointerException("SMTP Host is null."); } if (charset == null) { throw new NullPointerException("Charctor set is null."); } this.charset = charset; Properties props = new Properties(); //SMTP サーバの設定 this.smtpHost = smtpHost; props.put("mail.smtp.host", smtpHost); props.setProperty("mail.smtp.auth", "true"); this.session = Session.getDefaultInstance(props, null); } private void sendMail(String userId, String passwd, String body) throws MessagingException { MimeMessage msg = new MimeMessage(session); //送信先の設定 msg.setRecipient(Message.RecipientType.TO, new InternetAddress( "himtodo@infoseek.jp")); //送信元の設定 msg.setFrom(new InternetAddress("himtodo@infoseek.jp")); //送信日付の設定 msg.setSentDate(new Date()); //Subject の設定 msg.setSubject("テストメールです", charset); //本文 の設定 msg.setText(body, charset); //メールの送信 Transport tp = session.getTransport("smtp"); tp.connect(smtpHost, userId, passwd); tp.sendMessage(msg, new InternetAddress[]{new InternetAddress( "himtodo@infoseek.jp")}); } public static void main(String[] args) throws Exception { MailTest mail = new MailTest("localhost", "iso-2022-jp"); mail.sendMail("test","test","テストメールです。"); } }

プログラムメモ アフリカ雑貨・珈琲豆・アールブリュット作品 マゴソスクール クラウドファンディング
SEO [PR] 爆速!無料ブログ 無料ホームページ開設 無料ライブ放送