Last active
October 7, 2022 18:27
-
-
Save raupachz/771e2abae6e3696e08dcf56fe1a1228c to your computer and use it in GitHub Desktop.
JavaMail API with Amazon Simple Email Service (SES) using the SMTP Interface
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.sun.mail.smtp.SMTPTransport; | |
import java.io.IOException; | |
import java.util.Properties; | |
import javax.mail.Message; | |
import javax.mail.MessagingException; | |
import javax.mail.Session; | |
import javax.mail.internet.InternetAddress; | |
import javax.mail.internet.MimeMessage; | |
/** | |
* Sending mails using AWS SES SMTP Interface and JavaMail | |
* | |
* We assume the domain 'example.com' is verified in SES | |
*/ | |
public class Mail { | |
/* Your personal SMTP credentials */ | |
public static final String SMTP_SERVER = "email-smtp.eu-west-1.amazonaws.com"; // depends on your region | |
public static final String SMTP_USERNAME = "<your username>"; | |
public static final String SMTP_PASSWORD = "<your password>"; | |
public static void main(String args[]) throws MessagingException, IOException { | |
Properties props = new Properties(); | |
props.put("mail.transport.protocol", "smtp") | |
props.put("mail.smtp.host", SMTP_SERVER); | |
props.put("mail.smtp.port", "587"); | |
props.put("mail.smtp.starttls.enable", "true"); | |
props.put("mail.smtp.auth", "true"); | |
/* Return path for bounces and complaints. Pick an address you own */ | |
props.put("mail.smtp.from", "[email protected]"); | |
props.put("mail.smtp.connectiontimeout", "10000"); | |
props.put("mail.smtp.timeout", "10000"); | |
props.put("mail.smtp.writetimeout", "10000"); | |
Session session = Session.getDefaultInstance(props); | |
try (SMTPTransport transport = (SMTPTransport) session.getTransport()) { | |
transport.connect(SMTP_USERNAME, SMTP_PASSWORD); | |
MimeMessage msg = new MimeMessage(session); | |
msg.setFrom(new InternetAddress("[email protected]")); | |
msg.setRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]")); | |
msg.setSubject("Hello from SES"); | |
msg.setContent("<h1>Hello</h1>", "text/html; charset=utf-8"); | |
msg.saveChanges(); | |
transport.sendMessage(msg, msg.getAllRecipients()); | |
/* Log your SES message Id, AWS Support might need it */ | |
String serverResponse = transport.getLastServerResponse(); | |
String prefix = "250 Ok "; | |
if (serverResponse.startsWith(prefix)) { | |
String messageId = serverResponse.substring(prefix.length()); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment