The following example shows how to send an email through SMTP using Javamail.
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.2</version>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.6</version>
</dependency>
import javax.mail.*;
import javax.mail.internet.*;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;
//import java.util.HashMap;
//import java.util.Base64;
//import com.google.gson.GsonBuilder;
//import javax.activation.DataHandler;
//import javax.activation.FileDataSource;
public class SampleMail {
protected static String genMessageID(String mailFrom) {
// message-id should be like first-part@last-part
String[] mailInfo = mailFrom.split("@");
String domain = mailFrom;
int index = mailInfo.length - 1;
if (index >= 0) {
domain = mailInfo[index];
}
UUID uuid = UUID.randomUUID();
StringBuffer messageId = new StringBuffer();
messageId.append('<').append(uuid.toString()).append('@').append(domain).append('>');
return messageId.toString();
}
public static void main(String[] args) {
//Configure the environment properties for sending mail
final Properties props = new Properties();
// Indicates that SMTP sends mail and requires authentication
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", "smtpdm-ap-southeast-1.aliyuncs.com");
//Set port:
props.put("mail.smtp.port", "80");//Or "25". If ssl is used, remove the 80 or 25 port configuration and perform the following configuration:
//Encryption method:
//props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
//props.put("mail.smtp.socketFactory.port", "465");
//props.put("mail.smtp.port", "465");
props.put("mail.smtp.from", "test1***@example.net"); //mailfrom parameter
props.put("mail.user", "test1***@example.net");// The sender's account (the sending address created on the console)
props.put("mail.password", "******");// SMTP password of the sending address (select the sending address on the console for setting)
//props.put("mail.smtp.connectiontimeout", 1000);
// Build authorization information for SMTP authentication
Authenticator authenticator = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
String userName = props.getProperty("mail.user");
String password = props.getProperty("mail.password");
return new PasswordAuthentication(userName, password);
}
};
//Create a mail session using environment attributes and authorization information
Session mailSession = Session.getInstance(props, authenticator);
//mailSession.setDebug(true);//Enable debug mode
final String messageIDValue = genMessageID(props.getProperty("mail.user"));
//Create email message
MimeMessage message = new MimeMessage(mailSession) {
@Override
protected void updateMessageID() throws MessagingException {
//Set custom Message ID values
setHeader("Message-ID", messageIDValue);//Create Message-ID
}
};
try {
// Set the sender's email address and name. Fill in the sending address configured on the console. It is consistent with the above mail.user. The name can be customized.
InternetAddress from = new InternetAddress("sender address", "nickname");//The "from" parameter can set as other sender. Note: it is easy to be rejected by the receiver or enter the dustbin
message.setFrom(from);
//Optional. Set replyto address
Address[] a = new Address[1];
a[0] = new InternetAddress("test2***@example.net");
message.setReplyTo(a);
// Set recipient email address
InternetAddress to = new InternetAddress("recipient email address");
message.setRecipient(MimeMessage.RecipientType.TO, to);
//If it is sent to more than one person at the same time, the above two lines will be replaced by the following (because of some limitations of the receiving system, try to send it to one person at a time; at the same time, we limit the number of people allowed to send at a time, please refer to Limits):
//InternetAddress[] adds = new InternetAddress[2];
//adds[0] = new InternetAddress("recipient email address1");
//adds[1] = new InternetAddress("recipient email address2");
//message.setRecipients(Message.RecipientType.TO, adds);
message.setSentDate(new Date()); //Set time
String ccUser = "Cc Address";
// Set multiple CC addresses
if (null != ccUser && !ccUser.isEmpty()) {
@SuppressWarnings("static-access")
InternetAddress[] internetAddressCC = new InternetAddress().parse(ccUser);
message.setRecipients(Message.RecipientType.CC, internetAddressCC);
}
String bccUser = "Bcc Address";
// Set multiple Bcc addresses
if (null != bccUser && !bccUser.isEmpty()) {
@SuppressWarnings("static-access")
InternetAddress[] internetAddressBCC = new InternetAddress().parse(bccUser);
message.setRecipients(Message.RecipientType.BCC, internetAddressBCC);
}
//Set Message Header
message.setSubject("Test topic");
message.setContent("Test<br>content", "text/html;charset=UTF-8");//html Hypertext;// "text/plain;charset=UTF-8" //plain.
// //To enable the mail tracking service, use the following code to set the tracking link header. See the document "How can I enable data tracking feature?" for preconditions and constraints?"
// String tagName = "Test";
// HashMap<String, String> trace = new HashMap<>();
// //Here is the string "1"
// trace.put("OpenTrace", "1"); //Turn on email tracking
// trace.put("LinkTrace", "1"); //Click the URL tracking in the email
// trace.put("TagName", tagName); //Label created by console tagname
// String jsonTrace = new GsonBuilder().setPrettyPrinting().create().toJson(trace);
// //System.out.println(jsonTrace);
// String base64Trace = new String(Base64.getEncoder().encode(jsonTrace.getBytes()));
// //Set Tracking Link Header
// message.addHeader("X-AliDM-Trace", base64Trace);
// //Sample values in the original message eml:X-AliDM-Trace: eyJUYWdOYW1lIjoiVGVzdCIsIk9wZW5UcmFjZSI6IjEiLCJMaW5rVHJhY2UiOiIxIn0=
//Send attachments and content:
// BodyPart messageBodyPart = new MimeBodyPart();
// //messageBodyPart.setText("message<br>Text");//Set the content of the message, text
// messageBodyPart.setContent("Test<br>content", "text/html;charset=UTF-8");// plain:"text/plain;charset=UTF-8" //Set the content of the message
// //Create multiple messages
// Multipart multipart = new MimeMultipart();
// //Set Text Message Part
// multipart.addBodyPart(messageBodyPart);
// //Attachments part
// //When sending attachments, the total smtp email size should not exceed 15M, and the message part should be created.
// MimeBodyPart mimeBodyPart = new MimeBodyPart();
// //Set the file path to send attachments
// String filename = "C:\\Users\\test2.txt";
// FileDataSource source = new FileDataSource(filename);
// mimeBodyPart.setDataHandler(new DataHandler(source));
// //Handle the problem of garbled Chinese attachment name (attached file path)
// mimeBodyPart.setFileName(MimeUtility.encodeText("Test attachment"));
// mimeBodyPart.addHeader("Content-Transfer-Encoding", "base64");
// multipart.addBodyPart(mimeBodyPart);
// //Send a complete message with attachments
// message.setContent(multipart);
// // Send attachment code, end
// Send Mail
Transport.send(message);
} catch (MessagingException e) {
String err = e.getMessage();
// The message content is processed here in a fixed format
System.out.println(err);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}