メールの自動送信

メールの自動送信をしたい場合に、実機のメール機能を使うとメール送信前のメールアプリを起動して、送信ボタンを押す前のところまではできるけど、メール送信まではできない。

そこで、Gmailのsmtp機能を使って、メールを自動で送信する。何かの状況を探知してメールを送信するような場合に使えると思う。接続にGmailのアドレスとパスワードが必要でそれを送る必要がある。

実行する。

sendmailGmail = new SendmailGmail();

sendmailGmail.send(mail,””);

クラスを作る

public SendmailGmail(){
Properties props = new Properties();
props.put(“mail.smtp.host”, “smtp.gmail.com”); // SMTPサーバ名
props.put(“mail.host”, “smtp.gmail.com”); // 接続するホスト名
props.put(“mail.smtp.port”, “587”); // SMTPサーバポート
props.put(“mail.smtp.auth”, “true”); // smtp auth
props.put(“mail.smtp.starttls.enable”, “true”); // STTLS

// セッション
session = Session.getDefaultInstance(props);
session.setDebug(true);

}

public void send(String mail,String text){

msg = new MimeMessage(session);
try {
msg.setSubject(“メールタイトル”, “utf-8”);
msg.setFrom(new InternetAddress(“~@gmail.com”));
msg.setSender(new InternetAddress(“~@gmail.com”));
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(mail));
msg.setText(text, “utf-8”);

t = session.getTransport(“smtp”);
t.connect(“~@gmail.com”, “noisealert”);
//
} catch (MessagingException e) {
e.printStackTrace();
}

try {
t.sendMessage(msg, msg.getAllRecipients());
} catch (MessagingException e) {
e.printStackTrace();
}
}

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です