QNA > W > What Is The Recommended Way To Send Email Programmatically With Java?

What is the recommended way to send email programmatically with Java?

Yes, I will send e-mail to you with Java.

Give me your email id :)

Just kidding:

  1. import java.util.Properties; 
  2. import javax.mail.Message; 
  3. import javax.mail.MessagingException; 
  4. import javax.mail.Session; 
  5. import javax.mail.Transport; 
  6. importjavax.mail.internet.AddressException; 
  7. importjavax.mail.internet.InternetAddress; 
  8. import javax.mail.internet.MimeMessage; 
  9. public class SendMailTLS { 
  10. public static void main(String[] args) { 
  11. // To address 
  12. String to = "[email protected]"; 
  13. // If any CC email ids 
  14. String cc = "[email protected]"; 
  15. // If any BCC email ids 
  16. String bcc = "[email protected]"; 
  17. // Email Subject 
  18. String subject = "Java Discover"; 
  19. // Email content 
  20. String emailText = "Hi All, Welcome to Java Mail API"; 
  21. // Sending Email using Gmail SMTP 
  22. sendEmail(to, cc, bcc, subject, emailText); 
  23. } 
  24. public static void sendEmail(String to, String cc, String bcc, String subject, String emailText) { 
  25. // From address (Need Gmail ID) 
  26. String from = "[email protected]"; 
  27. // Password of from address 
  28. String password = "from_password"; 
  29. // Gmail host address 
  30. String host = "smtp.gmail.com"; 
  31. Properties props = System.getProperties(); 
  32. props.put("mail.smtp.host", host); 
  33. props.put("mail.smtp.socketFactory.port", "465"); 
  34. props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); 
  35. props.put("mail.smtp.auth", "true"); 
  36. props.put("mail.smtp.port", "465"); 
  37. props.put("mail.smtp.user", from); 
  38. props.put("password", password); 
  39. Session session = Session.getDefaultInstance(props, null); 
  40. MimeMessage msg = newMimeMessage(session); 
  41. try { 
  42. msg.setFrom(newInternetAddress(from)); 
  43. // Adding To address 
  44. msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false)); 
  45. // Adding CC email id 
  46. msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false)); 
  47. // Adding BCC email id 
  48. msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false)); 
  49. msg.setSubject(subject); 
  50. msg.setText(emailText); 
  51. Transport transport = session.getTransport("smtp"); 
  52. transport.connect(host, from, password); 
  53. transport.sendMessage(msg, msg.getAllRecipients()); 
  54. transport.close(); 
  55. System.out.println("Email was sent successfully....."); 
  56. } catch (AddressException e) { 
  57. e.printStackTrace(); 
  58. } catch (MessagingException e) { 
  59. e.printStackTrace(); 
  60. } 
  61. } 
  62. } 

Di Neddra Tatton

How to integrate PHPMailer with CodeIgniter 4 :: Cosa succede quando si apre un file per la lettura?
Link utili