Posted By

bcmoney on 02/22/13


Tagged

email mail java notification send in


Versions (?)

SendEmail.java


 / Published in: Java
 

URL: http://wiki.bcmoney-mobiletv.com/index.php?title=Email

Sends an Email message in Java. The properties file should look as follows:

############################################ Email server settings (default SMTP port is "25", but Gmail uses different one) ############################################

notificationFrom = [email protected]

notificationCC = [email protected]

notificationTo = [email protected]

notificationAuth = true

notificationSecurity = true

notificationHost = smtp.gmail.com

notificationPort = 587

  1. package tv.bcmoney.notify;
  2.  
  3. import java.io.FileInputStream;
  4. import java.io.IOException;
  5. import java.io.InputStream;
  6. import java.util.*;
  7. import javax.mail.*;
  8. import javax.mail.internet.*;
  9.  
  10. import org.apache.commons.logging.Log;
  11. import org.apache.commons.logging.LogFactory;
  12.  
  13.  
  14.  
  15.  
  16. /**
  17.  * SendEmail
  18.  * Sends an Email to the desired email address for particular reason, such as:
  19.  * 1. Mass-distributed Newsletter or promotional message (Marketing)
  20.  * 2. Support Mailing List for problem reports (Notification)
  21.  * 3. Automated confirmation message or to another Email listener program (Transaction)
  22.  * 4. Message expressly sent from one user to another (Interpersonal)
  23.  *
  24.  * @author bcbcope
  25.  */
  26. public class SendEmail {
  27.  
  28. //location of the properties file with server (SMTP/MIME/POP3/IMAP) settings
  29. private static String EMAIL_CONFIG = "META-INF/email.properties";
  30.  
  31. private static final Log log = LogFactory.getLog(SendEmail.class);
  32.  
  33. protected Session session = null;
  34.  
  35. private static Properties props = new Properties();
  36.  
  37. /* constructors */
  38. public SendEmail() {
  39. fetchConfig();
  40.  
  41. props.put("mail.smtp.auth", props.getProperty("notificationAuth"));
  42. props.put("mail.smtp.starttls.enable", props.getProperty("notificationSecurity"));
  43. props.put("mail.smtp.host", props.getProperty("notificationHost"));
  44. props.put("mail.smtp.port", props.getProperty("notificationPort"));
  45.  
  46. session = Session.getInstance(props, new Authenticator() {
  47. protected PasswordAuthentication getPasswordAuthentication() {
  48. return new PasswordAuthentication(props.getProperty("username"), props.getProperty("password"));
  49. }
  50. });
  51. }
  52.  
  53. /**
  54. * Open a specific text file containing mail server
  55. * parameters, and populate a corresponding Properties object.
  56. */
  57. private void fetchConfig() {
  58. InputStream is = null;
  59. try {
  60. //load properties file
  61. is = this.getClass().getClassLoader().getResourceAsStream(EMAIL_CONFIG);
  62. props.load(is);
  63. } catch (IOException ex) {
  64. log.error("Cannot open and load mail server properties file." + ex);
  65. } finally {
  66. try {
  67. if ( is != null ) is.close();
  68. } catch (IOException ex) {
  69. System.err.println( "Cannot close mail server properties file." );
  70. }
  71. }
  72. }
  73.  
  74. /**
  75. * Allows the connection configuration to be refreshed at runtime, instead of
  76. * requiring a restart.
  77. */
  78. public void refreshConfig() {
  79. props.clear();
  80. fetchConfig();
  81. }
  82.  
  83. /**
  84. * "send" method to send the message.
  85. */
  86. public void send(String subject, String body)
  87. {
  88. try
  89. {
  90. Session session = Session.getDefaultInstance(props, null);
  91. // Create a new message
  92. Message msg = new MimeMessage(session);
  93. // Set the FROM and TO fields
  94. msg.setFrom(new InternetAddress(props.getProperty("notificationFrom")));
  95. msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(props.getProperty("notificationTo"), false));
  96. // OPTIONALLY include any CC recipients too
  97. if (props.getProperty("notificationCC") != null) {
  98. msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(props.getProperty("notificationCC"), false));
  99. }
  100. // Set the subject and body text
  101. msg.setSubject(subject);
  102. msg.setText(body);
  103. // Set some other header information
  104. msg.setHeader("X-Mailer", props.getProperty("notificationMailer"));
  105. msg.setSentDate(new Date());
  106. // Send the message
  107. Transport.send(msg);
  108. log.info("Message sent OK.");
  109. } catch (MessagingException e) {
  110. log.error(e);
  111. throw new RuntimeException(e);
  112. } catch (Exception ex) {
  113. log.error(ex);
  114. }
  115. }
  116.  
  117. /**
  118. * send
  119. * Method to send the message with configurable parameters.
  120. */
  121. public void send(String to, String cc, String from, String subject, String body)
  122. {
  123. try
  124. {
  125. Session session = Session.getDefaultInstance(props, null);
  126. // Create a new message
  127. Message msg = new MimeMessage(session);
  128. // Set the FROM and TO fields
  129. msg.setFrom(new InternetAddress(from));
  130. msg.setRecipients(Message.RecipientType.TO,
  131. InternetAddress.parse(to, false));
  132. // OPTIONALLY include any CC recipients too
  133. if (cc != null) {
  134. msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
  135. }
  136. // Set the subject and body text
  137. msg.setSubject(subject);
  138. msg.setText(body);
  139. // Set some other header information
  140. msg.setHeader("X-Mailer", props.getProperty("notificationMailer"));
  141. msg.setSentDate(new Date());
  142. // Send the message
  143. Transport.send(msg);
  144. log.info("Message sent OK.");
  145. } catch (MessagingException e) {
  146. log.error(e);
  147. throw new RuntimeException(e);
  148. } catch (Exception ex) {
  149. log.error(ex);
  150. }
  151. }
  152.  
  153. /******************************************************************************
  154.  * TEST */
  155. public static void main(String[] args) {
  156. SendEmail email = new SendEmail();
  157. String subject = "Test Message";
  158. String body = "Hey, this is just a test message from JAVA.";
  159. email.send(subject, body);
  160. }
  161.  
  162. /* SANITY CHECK A SIMPLE URL REQUEST (outside connection capability)
  163.   public static void main (String[] args) throws IOException {
  164.   try {
  165.   java.net.URL url = new java.net.URL("http://my.medavie.bluecross.ca/"); //external site such as "http://www.drudgereport.com" does not work
  166.   java.io.BufferedReader in = new java.io.BufferedReader(new java.io.InputStreamReader(url.openStream()));
  167.   String str;
  168.  
  169.   while ((str = in.readLine()) != null) {
  170.   System.out.println(str);
  171.   }
  172.  
  173.   in.close();
  174.   } catch (java.net.MalformedURLException e) { e.printStackTrace(); }
  175.   catch (IOException e) { e.printStackTrace(); }
  176.   }
  177. */
  178. }

Report this snippet  

You need to login to post a comment.