SESでメールを送信するもう1つの方法
を試してみる
サンプル
Sample02.java
import java.util.Properties; import com.amazonaws.auth.AWSCredentials; import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.regions.Region; import com.amazonaws.regions.Regions; import com.amazonaws.services.simpleemail.AWSJavaMailTransport; import com.amazonaws.services.simpleemail.AmazonSimpleEmailService; import com.amazonaws.services.simpleemail.AmazonSimpleEmailServiceClient; import com.amazonaws.services.simpleemail.model.ListVerifiedEmailAddressesResult; import com.amazonaws.services.simpleemail.model.VerifyEmailAddressRequest; import javax.mail.Message; import javax.mail.MessagingException; 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 Sample02 { private static final String ACCESS_KEY = "アクセスキー"; private static final String SECRET_ACCESS_KEY = "シークレットアクセスキー"; public static void main(String[] args) throws AddressException, MessagingException { String TO = "送信先のメール"; String FROM = "送信元のメール"; String SUBJECT = "テストメール"; String BODY = "テストメールです。"; // 認証 AWSCredentials credentials = new BasicAWSCredentials(ACCESS_KEY, SECRET_ACCESS_KEY); AmazonSimpleEmailService ses = new AmazonSimpleEmailServiceClient(credentials); ses.setRegion(Region.getRegion(Regions.US_WEST_2)); // 送信元認証 verifyEmailAddress(ses, FROM); verifyEmailAddress(ses, TO); // 設定 Properties props = new Properties(); props.setProperty("mail.transport.protocol", "aws"); props.setProperty("mail.aws.user", credentials.getAWSAccessKeyId()); props.setProperty("mail.aws.password", credentials.getAWSSecretKey()); props.setProperty("mail.aws.host", "email.us-west-2.amazonaws.com"); Session session = Session.getDefaultInstance(props); // メッセージ作成 Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress(FROM)); msg.addRecipient(Message.RecipientType.TO, new InternetAddress(TO)); msg.setSubject(SUBJECT); msg.setText(BODY); msg.saveChanges(); // 送信 Transport t = new AWSJavaMailTransport(session, null); try { t.connect(); t.sendMessage(msg, null); } finally { t.close(); } } // 認証 private static void verifyEmailAddress(AmazonSimpleEmailService ses, String address) { ListVerifiedEmailAddressesResult verifiedEmails = ses.listVerifiedEmailAddresses(); if (verifiedEmails.getVerifiedEmailAddresses().contains(address)) return; ses.verifyEmailAddress(new VerifyEmailAddressRequest().withEmailAddress(address)); } }
認証していない場合
認証メールを送信して認証することで対応可能とのこと
hostでリージョンのエンドポイントを指定する。
何も指定していないとus-east-1でしか送信していない感じに見える。