Casa > 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. public static void sendEmail(String to, String cc, String bcc, String subject, String emailText) { 
  24. // From address (Need Gmail ID) 
  25. String from = "[email protected]"; 
  26. // Password of from address 
  27. String password = "from_password"; 
  28. // Gmail host address 
  29. String host = "smtp.gmail.com"; 
  30. Properties props = System.getProperties(); 
  31. props.put("mail.smtp.host", host); 
  32. props.put("mail.smtp.socketFactory.port", "465"); 
  33. props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); 
  34. props.put("mail.smtp.auth", "true"); 
  35. props.put("mail.smtp.port", "465"); 
  36. props.put("mail.smtp.user", from); 
  37. props.put("password", password); 
  38. Session session = Session.getDefaultInstance(props, null); 
  39. MimeMessage msg = newMimeMessage(session); 
  40. try { 
  41. msg.setFrom(newInternetAddress(from)); 
  42. // Adding To address 
  43. msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false)); 
  44. // Adding CC email id 
  45. msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false)); 
  46. // Adding BCC email id 
  47. msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false)); 
  48. msg.setSubject(subject); 
  49. msg.setText(emailText); 
  50. Transport transport = session.getTransport("smtp"); 
  51. transport.connect(host, from, password); 
  52. transport.sendMessage(msg, msg.getAllRecipients()); 
  53. transport.close(); 
  54. System.out.println("Email was sent successfully....."); 
  55. } catch (AddressException e) { 
  56. e.printStackTrace(); 
  57. } catch (MessagingException e) { 
  58. e.printStackTrace(); 

De Millda

O que acontece quando você abre um arquivo para leitura? :: Como abrir um arquivo IMSCC