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();
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());
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","テストメールです。");
}
}
|