code_junkie

How do I send an SMTP Message from Java?

Nov 10th, 2011
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.08 KB | None | 0 0
  1. /*
  2. *
  3. */
  4.  
  5. import java.io.*;
  6. import java.net.InetAddress;
  7. import java.util.Properties;
  8. import java.util.Date;
  9.  
  10. import javax.mail.*;
  11.  
  12. import javax.mail.internet.*;
  13.  
  14. import com.sun.mail.smtp.*;
  15.  
  16.  
  17. public class Distribution {
  18.  
  19. public static void main(String args[]) throws Exception {
  20. Properties props = System.getProperties();
  21. props.put("mail.smtps.host","smtp.gmail.com");
  22. props.put("mail.smtps.auth","true");
  23. Session session = Session.getInstance(props, null);
  24. Message msg = new MimeMessage(session);
  25. msg.setFrom(new InternetAddress("[email protected]"));;
  26. msg.setRecipients(Message.RecipientType.TO,
  27. InternetAddress.parse("[email protected]", false));
  28. msg.setSubject("Heisann "+System.currentTimeMillis());
  29. msg.setText("Med vennlig hilsennTov Are Jacobsen");
  30. msg.setHeader("X-Mailer", "Tov Are's program");
  31. msg.setSentDate(new Date());
  32. SMTPTransport t =
  33. (SMTPTransport)session.getTransport("smtps");
  34. t.connect("smtp.gmail.com", "[email protected]", "<insert password here>");
  35. t.sendMessage(msg, msg.getAllRecipients());
  36. System.out.println("Response: " + t.getLastServerResponse());
  37. t.close();
  38. }
  39. }
  40.  
  41. MailQue.queMail(MimeMessage message)
  42.  
  43. //Set the host smtp address
  44. Properties props = new Properties();
  45. props.put("mail.smtp.host", "smtp.jcom.net");
  46.  
  47. // create some properties and get the default Session
  48. Session session = Session.getDefaultInstance(props,
  49.  
  50. // create a message
  51. Message msg = new MimeMessage(session);
  52.  
  53. // set the from and to address
  54. InternetAddress addressFrom = new InternetAddress(from);
  55. msg.setFrom(addressFrom);
  56.  
  57. InternetAddress[] addressTo = new InternetAddress[recipients.length];
  58. for (int i = 0; i < recipients.length; i++)
  59. {
  60. addressTo[i] = new InternetAddress(recipients[i]);
  61. }
  62. msg.setRecipients(Message.RecipientType.TO,
  63.  
  64. // Optional : You can also set your custom headers in the Email if
  65.  
  66. // Setting the Subject and Content Type
  67. msg.setSubject(subject);
  68. msg.setContent(message, "text/plain");
  69. Transport.send(msg); }
Add Comment
Please, Sign In to add comment