daily pastebin goal
6%
SHARE
TWEET

Untitled

a guest May 31st, 2017 510 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2.  * Email.java
  3.  *
  4.  * Version: $Revision: 3705 $
  5.  *
  6.  * Date: $Date: 2009-04-11 19:02:24 +0200 (Sat, 11 Apr 2009) $
  7.  *
  8.  * Copyright (c) 2002-2005, Hewlett-Packard Company and Massachusetts
  9.  * Institute of Technology.  All rights reserved.
  10.  *
  11.  * Redistribution and use in source and binary forms, with or without
  12.  * modification, are permitted provided that the following conditions are
  13.  * met:
  14.  *
  15.  * - Redistributions of source code must retain the above copyright
  16.  * notice, this list of conditions and the following disclaimer.
  17.  *
  18.  * - Redistributions in binary form must reproduce the above copyright
  19.  * notice, this list of conditions and the following disclaimer in the
  20.  * documentation and/or other materials provided with the distribution.
  21.  *
  22.  * - Neither the name of the Hewlett-Packard Company nor the name of the
  23.  * Massachusetts Institute of Technology nor the names of their
  24.  * contributors may be used to endorse or promote products derived from
  25.  * this software without specific prior written permission.
  26.  *
  27.  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  28.  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  29.  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  30.  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  31.  * HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  32.  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  33.  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
  34.  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  35.  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
  36.  * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
  37.  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
  38.  * DAMAGE.
  39.  */
  40. package org.dspace.core;
  41.  
  42. import java.io.File;
  43. import java.text.MessageFormat;
  44. import java.util.ArrayList;
  45. import java.util.Date;
  46. import java.util.Iterator;
  47. import java.util.List;
  48. import java.util.Properties;
  49.  
  50. import javax.activation.DataHandler;
  51. import javax.activation.FileDataSource;
  52. import javax.mail.Address;
  53. import javax.mail.Authenticator;
  54. import javax.mail.BodyPart;
  55. import javax.mail.Message;
  56. import javax.mail.MessagingException;
  57. import javax.mail.Multipart;
  58. import javax.mail.PasswordAuthentication;
  59. import javax.mail.Session;
  60. import javax.mail.Transport;
  61. import javax.mail.internet.InternetAddress;
  62. import javax.mail.internet.MimeBodyPart;
  63. import javax.mail.internet.MimeMessage;
  64. import javax.mail.internet.MimeMultipart;
  65.  
  66. /**
  67.  * Class representing an e-mail message, also used to send e-mails.
  68.  * <P>
  69.  * Typical use:
  70.  * <P>
  71.  * <code>Email email = ConfigurationManager.getEmail(name);</code><br>
  72.  * <code>email.addRecipient("foo@bar.com");</code><br>
  73.  * <code>email.addArgument("John");</code><br>
  74.  * <code>email.addArgument("On the Testing of DSpace");</code><br>
  75.  * <code>email.send();</code><br>
  76.  * <P>
  77.  * <code>name</code> is the name of an email template in
  78.  * <code>dspace-dir/config/emails/</code> (which also includes the subject.)
  79.  * <code>arg0</code> and <code>arg1</code> are arguments to fill out the
  80.  * message with.
  81.  * <P>
  82.  * Emails are formatted using <code>java.text.MessageFormat.</code>
  83.  * Additionally, comment lines (starting with '#') are stripped, and if a line
  84.  * starts with "Subject:" the text on the right of the colon is used for the
  85.  * subject line. For example:
  86.  * <P>
  87.  *
  88.  * <pre>
  89.  *    
  90.  *     # This is a comment line which is stripped
  91.  *     #
  92.  *     # Parameters:   {0}  is a person's name
  93.  *     #               {1}  is the name of a submission
  94.  *     #
  95.  *     Subject: Example e-mail
  96.  *    
  97.  *     Dear {0},
  98.  *    
  99.  *     Thank you for sending us your submission "{1}".
  100.  *    
  101.  * </pre>
  102.  *
  103.  * <P>
  104.  * If the example code above was used to send this mail, the resulting mail
  105.  * would have the subject <code>Example e-mail</code> and the body would be:
  106.  * <P>
  107.  *
  108.  * <pre>
  109.  *    
  110.  *    
  111.  *     Dear John,
  112.  *    
  113.  *     Thank you for sending us your submission "On the Testing of DSpace".
  114.  *    
  115.  * </pre>
  116.  *
  117.  * <P>
  118.  * Note that parameters like <code>{0}</code> cannot be placed in the subject
  119.  * of the e-mail; they won't get filled out.
  120.  *
  121.  *
  122.  * @author Robert Tansley
  123.  * @author Jim Downing - added attachment handling code
  124.  * @version $Revision: 3705 $
  125.  */
  126. public class Email
  127. {
  128.     /*
  129.      * Implementation note: It might be necessary to add a quick utility method
  130.      * like "send(to, subject, message)". We'll see how far we get without it -
  131.      * having all emails as templates in the config allows customisation and
  132.      * internationalisation.
  133.      *
  134.      * Note that everything is stored and the run in send() so that only send()
  135.      * throws a MessagingException.
  136.      */
  137.  
  138.     /** The content of the message */
  139.     private String content;
  140.  
  141.     /** The subject of the message */
  142.     private String subject;
  143.  
  144.     /** The arguments to fill out */
  145.     private List arguments;
  146.  
  147.     /** The recipients */
  148.     private List recipients;
  149.  
  150.     /** Reply to field, if any */
  151.     private String replyTo;
  152.  
  153.     private List attachments;
  154.  
  155.     /** The character set this message will be sent in */
  156.     private String charset;
  157.    
  158.     /**
  159.      * Create a new email message.
  160.      */
  161.     Email()
  162.     {
  163.         arguments = new ArrayList(50);
  164.         recipients = new ArrayList(50);
  165.         attachments = new ArrayList(10);
  166.         subject = "";
  167.         content = "";
  168.         replyTo = null;
  169.         charset = null;
  170.     }
  171.  
  172.     /**
  173.      * Add a recipient
  174.      *
  175.      * @param email
  176.      *            the recipient's email address
  177.      */
  178.     public void addRecipient(String email)
  179.     {
  180.         recipients.add(email);
  181.     }
  182.  
  183.     /**
  184.      * Set the content of the message. Setting this "resets" the message
  185.      * formatting -<code>addArgument</code> will start. Comments and any
  186.      * "Subject:" line must be stripped.
  187.      *
  188.      * @param cnt
  189.      *            the content of the message
  190.      */
  191.     void setContent(String cnt)
  192.     {
  193.         content = cnt;
  194.         arguments = new ArrayList();
  195.     }
  196.  
  197.     /**
  198.      * Set the subject of the message
  199.      *
  200.      * @param s
  201.      *            the subject of the message
  202.      */
  203.     void setSubject(String s)
  204.     {
  205.         subject = s;
  206.     }
  207.  
  208.     /**
  209.      * Set the reply-to email address
  210.      *
  211.      * @param email
  212.      *            the reply-to email address
  213.      */
  214.     public void setReplyTo(String email)
  215.     {
  216.         replyTo = email;
  217.     }
  218.  
  219.     /**
  220.      * Fill out the next argument in the template
  221.      *
  222.      * @param arg
  223.      *            the value for the next argument
  224.      */
  225.     public void addArgument(Object arg)
  226.     {
  227.         arguments.add(arg);
  228.     }
  229.  
  230.     public void addAttachment(File f, String name)
  231.     {
  232.         attachments.add(new FileAttachment(f, name));
  233.     }
  234.  
  235.     public void setCharset(String cs)
  236.     {
  237.         charset = cs;
  238.     }
  239.  
  240.     /**
  241.      * "Reset" the message. Clears the arguments and recipients, but leaves the
  242.      * subject and content intact.
  243.      */
  244.     public void reset()
  245.     {
  246.         arguments = new ArrayList(50);
  247.         recipients = new ArrayList(50);
  248.         attachments = new ArrayList(10);
  249.         replyTo = null;
  250.         charset = null;
  251.     }
  252.  
  253.     /**
  254.      * Sends the email.
  255.      *
  256.      * @throws MessagingException
  257.      *             if there was a problem sending the mail.
  258.      */
  259.     public void send() throws MessagingException
  260.     {
  261.         // Get the mail configuration properties
  262.         String server = ConfigurationManager.getProperty("mail.server");
  263.         String from = ConfigurationManager.getProperty("mail.from.address");
  264.  
  265.         // Set up properties for mail session
  266.         Properties props = System.getProperties();
  267.         props.put("mail.smtp.host", server);
  268.  
  269.         // Set the port number for the mail server
  270.         String portNo = ConfigurationManager.getProperty("mail.server.port");
  271.         if (portNo == null)
  272.         {
  273.             portNo = "25";
  274.         }
  275.         props.put("mail.smtp.port", portNo.trim());
  276.  
  277.         // If no character set specified, attempt to retrieve a default
  278.         if (charset == null)
  279.         {
  280.             charset = ConfigurationManager.getProperty("mail.charset");    
  281.         }
  282.  
  283.         // Get session
  284.         Session session;
  285.        
  286.         // Get the SMTP server authentication information
  287.         String username = ConfigurationManager.getProperty("mail.server.username");
  288.         String password = ConfigurationManager.getProperty("mail.server.password");
  289.        
  290.         if (username != null)
  291.         {
  292.             props.put("mail.smtp.auth", "true");
  293.             SMTPAuthenticator smtpAuthenticator = new SMTPAuthenticator(
  294.                     username, password);
  295.             session = Session.getDefaultInstance(props, smtpAuthenticator);
  296.         }
  297.         else
  298.         {
  299.             session = Session.getDefaultInstance(props);
  300.         }
  301.  
  302.         // Create message
  303.         MimeMessage message = new MimeMessage(session);
  304.  
  305.         // Set the recipients of the message
  306.         Iterator i = recipients.iterator();
  307.  
  308.         while (i.hasNext())
  309.         {
  310.             message.addRecipient(Message.RecipientType.TO, new InternetAddress(
  311.                     (String) i.next()));
  312.         }
  313.  
  314.         // Format the mail message
  315.         Object[] args = arguments.toArray();
  316.         String fullMessage = MessageFormat.format(content, args);
  317.         Date date = new Date();
  318.  
  319.         message.setSentDate(date);
  320.         message.setFrom(new InternetAddress(from));
  321.         message.setSubject(subject);
  322.         if (attachments.isEmpty())
  323.         {
  324.             // If a character set has been specified, or a default exists
  325.             if (charset != null)
  326.             {
  327.                 message.setText(fullMessage, charset);
  328.             }
  329.             else
  330.             {
  331.                 message.setText(fullMessage);
  332.             }
  333.         }
  334.         else
  335.         {
  336.             Multipart multipart = new MimeMultipart();
  337.             // create the first part of the email
  338.             BodyPart messageBodyPart = new MimeBodyPart();
  339.             messageBodyPart.setText(fullMessage);
  340.             multipart.addBodyPart(messageBodyPart);
  341.  
  342.             for (Iterator iter = attachments.iterator(); iter.hasNext();)
  343.             {
  344.                 FileAttachment f = (FileAttachment) iter.next();
  345.                 // add the file
  346.                 messageBodyPart = new MimeBodyPart();
  347.                 messageBodyPart.setDataHandler(new DataHandler(
  348.                         new FileDataSource(f.file)));
  349.                 messageBodyPart.setFileName(f.name);
  350.                 multipart.addBodyPart(messageBodyPart);
  351.             }
  352.             message.setContent(multipart);
  353.         }
  354.  
  355.         if (replyTo != null)
  356.         {
  357.             Address[] replyToAddr = new Address[1];
  358.             replyToAddr[0] = new InternetAddress(replyTo);
  359.             message.setReplyTo(replyToAddr);
  360.         }
  361.  
  362.         Transport.send(message);
  363.     }
  364.  
  365.     /**
  366.      * Utility struct class for handling file attachments.
  367.      *
  368.      * @author ojd20
  369.      *
  370.      */
  371.     private class FileAttachment
  372.     {
  373.         public FileAttachment(File f, String n)
  374.         {
  375.             this.file = f;
  376.             this.name = n;
  377.         }
  378.  
  379.         File file;
  380.  
  381.         String name;
  382.     }
  383.    
  384.     /**
  385.      * Inner Class for SMTP authentication information
  386.      */
  387.     private class SMTPAuthenticator extends Authenticator
  388.     {
  389.         // User name
  390.         private String name;
  391.        
  392.         // Password
  393.         private String password;
  394.        
  395.         public SMTPAuthenticator(String n, String p)
  396.         {
  397.             name = n;
  398.             password = p;
  399.         }
  400.        
  401.         protected PasswordAuthentication getPasswordAuthentication()
  402.         {
  403.             return new PasswordAuthentication(name, password);
  404.         }
  405.     }
  406. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top