edit-icon download-icon

SMTP - Java

Last Updated: Dec 15, 2017

The following example shows how to send an email through SMTP using Javamail.

  1. import javax.mail.*;
  2. import javax.mail.internet.InternetAddress;
  3. import javax.mail.internet.MimeMessage;
  4. import java.util.Properties;
  5. public class SampleMail {
  6. private static final String ALIDM_SMTP_HOST = "smtpdm.aliyun.com";
  7. private static final int ALIDM_SMTP_PORT = 25;//or 80
  8. public static void main(String[] args) {
  9. // Configure the mail environment properties
  10. final Properties props = new Properties();
  11. // Indicate that identity authentication is required for sending mails via SMTP
  12. props.put("mail.smtp.auth", "true");
  13. props.put("mail.smtp.host", ALIDM_SMTP_HOST);
  14. props.put("mail.smtp.port", ALIDM_SMTP_PORT);
  15. // If SSL is used, remove the configuration of using Port 25, as follows:
  16. // props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
  17. // props.put("mail.smtp.socketFactory.port", "465");
  18. // props.put("mail.smtp.port", "465");
  19. // The sender account
  20. props.put("mail.user", "***");
  21. // The password required for accessing the SMTP service.
  22. props.put("mail.password", "***");
  23. // Construct the authentication information for SMTP identity authentication.
  24. Authenticator authenticator = new Authenticator() {
  25. @Override
  26. protected PasswordAuthentication getPasswordAuthentication() {
  27. // Username and password
  28. String userName = props.getProperty("mail.user");
  29. String password = props.getProperty("mail.password");
  30. return new PasswordAuthentication(userName, password);
  31. }
  32. };
  33. // Create the mail session using the environmental attributes and authentication information.
  34. Session mailSession = Session.getInstance(props, authenticator);
  35. //mailSession.setDebug(true);
  36. // Create the mail message.
  37. MimeMessage message = new MimeMessage(mailSession);
  38. try {
  39. // Set the sender.
  40. InternetAddress from = new InternetAddress("***");
  41. message.setFrom(from);
  42. Address[] a = new Address[1];
  43. a[0] = new InternetAddress("***");
  44. message.setReplyTo(a);
  45. // Set the recipient.
  46. InternetAddress to = new InternetAddress("***");
  47. message.setRecipient(MimeMessage.RecipientType.TO, to);
  48. // Set the mail subject.
  49. message.setSubject("Test mail");
  50. // Set the mail body content.
  51. message.setContent("Test HTML mail", "text/html;charset=UTF-8");
  52. // Send the mail.
  53. Transport.send(message);
  54. }
  55. catch (MessagingException e) {
  56. String err = e.getMessage();
  57. // Here to deal with the message content, format is fixed.
  58. System.out.println(err);
  59. }
  60. }
  61. }
Thank you! We've received your feedback.