Skip to content

Instantly share code, notes, and snippets.

@maji-KY
Created October 1, 2011 14:31
Show Gist options
  • Save maji-KY/1256110 to your computer and use it in GitHub Desktop.
Save maji-KY/1256110 to your computer and use it in GitHub Desktop.
JavaMail Example
//staticインポート...
import static javax.mail.Message.RecipientType.TO;
import java.io.IOException;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendJavaMail {
public static void main(String[] args) throws AddressException, MessagingException, IOException {
Properties props = new Properties();
//smptサーバに関する設定
props.setProperty("mail.smtp.host", "smtp.example.com");
props.setProperty("mail.smtp.port", "587");
props.setProperty("mail.smtp.auth", "true");
//タイムアウトも一応
props.setProperty("mail.smtp.connectiontimeout", "5000");
props.setProperty("mail.smtp.timeout", "5000");
//必要性はよくわからないけど、JavaMailはMessage-IDにこの値を付加するから一応
props.setProperty("mail.user", "majiky");
props.setProperty("mail.host", "smtp.example.com");
//サーバとの会話内容を出力してくれる!
props.setProperty("mail.debug", "true");
//パスワードを保持するクラスを作る必要がある?
class PasswordAuthenticatior extends Authenticator{
private String username;
private String password;
PasswordAuthenticatior(String username, String password) {
this.username = username;
this.password = password;
}
@Override
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
}
//パスワード認証つきのセッションを作成
Session session = Session.getDefaultInstance(
props,
new PasswordAuthenticatior("majiky","**passwd**")
);
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("[email protected]"));
msg.setSender(new InternetAddress("[email protected]"));
//TOを設定。CCとBCCも設定できるよ☆
msg.setRecipient(TO, new InternetAddress("[email protected]"));
msg.setSubject("メールを送った件について", "utf-8");
msg.setText("メールを送りました!");
//メッセージをストリームに書き出すメソッド。ソースが見れるぜ?
msg.writeTo(System.out);
Transport.send(msg);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment