Guest User

Untitled

a guest
Nov 19th, 2017
400
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.37 KB | None | 0 0
  1. import java.util.Properties;
  2.  
  3. import javax.mail.Authenticator;
  4. import javax.mail.Message;
  5. import javax.mail.PasswordAuthentication;
  6. import javax.mail.Session;
  7. import javax.mail.Transport;
  8. import javax.mail.internet.InternetAddress;
  9. import javax.mail.internet.MimeMessage;
  10.  
  11. public class SimpleEmail {
  12.  
  13. public String smtpHostname;
  14. public String smtpPort;
  15. public String smtpUser;
  16. public String smtpPassword;
  17. public String fromAddress;
  18. public String toAddress;
  19. public String useTLS = "false";
  20. public String useAuthentication = "true";
  21.  
  22. public static void main(String[] args) throws Exception{
  23. SimpleEmail mail01 = new SimpleEmail();
  24. mail01.smtpHostname = "smtpservername";
  25. mail01.smtpPort = "587";
  26. mail01.fromAddress = "email@example.org";
  27. mail01.smtpUser = "domain\\username";
  28. mail01.smtpPassword = "password";
  29. mail01.toAddress = "email@example.org";
  30. mail01.sendEmail();
  31. }
  32.  
  33. public void sendEmail() throws Exception{
  34. // TODO check if all properties where set
  35. Properties props = new Properties();
  36. props.setProperty("mail.transport.protocol", "smtp");
  37. props.setProperty("mail.smtp.port", smtpPort);
  38. props.setProperty("mail.smtp.starttls.enable", useTLS);
  39. props.setProperty("mail.smtp.host", smtpHostname);
  40. props.setProperty("mail.smtp.auth", useAuthentication);
  41.  
  42. Authenticator auth = new SMTPAuthenticator();
  43. Session mailSession = Session.getDefaultInstance(props, auth);
  44. // uncomment for debugging infos to stdout
  45. // mailSession.setDebug(true);
  46. Transport transport = mailSession.getTransport();
  47.  
  48. MimeMessage message = new MimeMessage(mailSession);
  49. message.setContent("This is a test", "text/plain");
  50. message.setFrom(new InternetAddress(fromAddress));
  51. message.addRecipient(Message.RecipientType.TO,
  52. new InternetAddress(toAddress));
  53.  
  54. transport.connect();
  55. transport.sendMessage(message,
  56. message.getRecipients(Message.RecipientType.TO));
  57. transport.close();
  58. }
  59.  
  60. private class SMTPAuthenticator extends Authenticator {
  61. public PasswordAuthentication getPasswordAuthentication() {
  62. String username = smtpUser;
  63. String password = smtpPassword;
  64. return new PasswordAuthentication(username, password);
  65. }
  66. }
  67. }
Add Comment
Please, Sign In to add comment