【注意】ここで紹介しているプログラムは、たまたま名前がカブってますが、UnderDone さんによるサービス FeedMail とはまったくの別物です。以下の内容について、UnderDone さんに問い合わせたりしないようにお願いします。
自作版「RSS→メール」アプリケーションの 3 クラス目。メールを発信する部分。JavaMail にほとんどおまかせ。その部分も、田中宏和による下記ページからのコピペなので、僕はほとんど何もしてない。もはや自作とさえ言えないレベルかも。
- JavaでHello World JavaMail(SMTP)編
- http://www.hellohiro.com/javamail.htm
ちなみに、自分の使ってる環境では SMTP 発信にパスワード認証が必要だったので、そのように作ってある。パスワード認証を使用しない環境では、このままだと動かないはず。
import java.io.IOException;
import java.util.Properties;
import java.util.Date;
import javax.mail.Session;
import javax.mail.PasswordAuthentication;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.Transport;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.InternetAddress;
public class MailOutput {
String smtpHost;
String senderAddress;
String senderName;
String recipientAddress;
String mailTitle;
volatile String smtpUserID;
volatile String smtpPassword;
public MailOutput(Properties config) {
// TODO: リフレクションで
this.smtpHost = config.getProperty("smtp.host");
this.senderAddress = config.getProperty("sender.address");
this.senderName = config.getProperty("sender.name");
this.recipientAddress = config.getProperty("recipient.address");
this.mailTitle = config.getProperty("mail.title");
this.smtpUserID = config.getProperty("smtp.userid");
this.smtpPassword = config.getProperty("smtp.password");
}
public void send(String text) throws IOException, FeedMailException {
try {
Properties props = System.getProperties();
props.setProperty("mail.smtp.auth", "true");
// SMTPサーバーのアドレスを指定
props.put("mail.smtp.host", smtpHost);
PasswordAuthenticator auth = new PasswordAuthenticator();
auth.setPasswordAuthentication(new PasswordAuthentication(this.smtpUserID, this.smtpPassword));
Session session = Session.getDefaultInstance(props, auth);
session.setDebug(true);
MimeMessage mimeMessage = new MimeMessage(session);
// 送信元メールアドレスと送信者名を指定
mimeMessage.setFrom(new InternetAddress(senderAddress, senderName, "iso-2022-jp"));
// 送信先メールアドレスを指定
mimeMessage.setRecipients(Message.RecipientType.TO, recipientAddress);
// メールのタイトルを指定
mimeMessage.setSubject(mailTitle,"iso-2022-jp");
// メールの内容を指定
mimeMessage.setText(text, "iso-2022-jp");
// メールの形式を指定
mimeMessage.setHeader("Content-Type", "text/plain");
// 送信日付を指定
mimeMessage.setSentDate(new Date());
// 送信します
Transport.send(mimeMessage);
} catch (IOException e) {
throw e;
} catch (Exception e) {
throw new FeedMailException(e);
}
}
static class PasswordAuthenticator extends Authenticator {
private PasswordAuthentication authentication;
public void setPasswordAuthentication(PasswordAuthentication authentication) {
this.authentication = authentication;
}
protected PasswordAuthentication getPasswordAuthentication() {
System.out.println("auth>> " + authentication.getUserName() + authentication.getPassword());
return this.authentication;
}
}
}