View Javadoc

1   /*
2    * Created on Jul 21, 2004 
3    * 
4    *   Magic-Project is a turn based strategy simulator
5    *   Copyright (C) 2003-2007 Fabrice Daugan
6    *
7    *   This program is free software; you can redistribute it and/or modify it 
8    * under the terms of the GNU General Public License as published by the Free 
9    * Software Foundation; either version 2 of the License, or (at your option) any
10   * later version.
11   *
12   *   This program is distributed in the hope that it will be useful, but WITHOUT 
13   * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
14   * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more 
15   * details.
16   *
17   *   You should have received a copy of the GNU General Public License along  
18   * with this program; if not, write to the Free Software Foundation, Inc., 
19   * 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20   * 
21   */
22  package net.sf.magicproject.mail;
23  
24  import java.io.File;
25  import java.util.List;
26  import java.util.Properties;
27  
28  import javax.activation.DataHandler;
29  import javax.activation.FileDataSource;
30  import javax.mail.Authenticator;
31  import javax.mail.Message;
32  import javax.mail.Part;
33  import javax.mail.PasswordAuthentication;
34  import javax.mail.Session;
35  import javax.mail.Transport;
36  import javax.mail.internet.InternetAddress;
37  import javax.mail.internet.MimeBodyPart;
38  import javax.mail.internet.MimeMessage;
39  import javax.mail.internet.MimeMultipart;
40  
41  import net.sf.magicproject.tools.Configuration;
42  import net.sf.magicproject.tools.MToolKit;
43  
44  /***
45   * To send a mail.
46   * 
47   * @author <a href="mailto:fabdouglas@users.sourceforge.net">Fabrice Daugan </a>
48   * @since 0.90
49   */
50  public final class MailUtils {
51  
52  	/***
53  	 * Create a new instance of this class.
54  	 */
55  	private MailUtils() {
56  		super();
57  	}
58  
59  	/***
60  	 * 
61  	 */
62  	public static final String DEFAULT_CONTENT_TYPE = "text/html";
63  
64  	/***
65  	 * @param userName
66  	 * @param from
67  	 * @param to
68  	 * @param message
69  	 * @param contentType
70  	 * @param subject
71  	 * @param attachments
72  	 * @param headers
73  	 * @param mailerUser
74  	 * @param hostName
75  	 * @return a MIME message
76  	 */
77  	public static MimeMessage sendEmail(String userName, String from,
78  			String[] to, String message, String contentType, String subject,
79  			List<String> attachments, Header[] headers, String mailerUser,
80  			String hostName) {
81  
82  		final Properties props = System.getProperties();
83  		props.put("user.name", userName);
84  		props.put("mail.user", userName);
85  		// props.put("user.passwd", "secret");
86  		// props.put("user.psswd", "secret");
87  		// props.put("user.pwd", "secret");
88  		// props.put("mail.smtp.password", "secret");
89  		// props.put("mail.smtp.auth", "true");
90  		// props.put("mail.smtp.port", "25");
91  		props.put("mail.smtp.user", userName);
92  		props.put("mail.smtp.host", hostName);
93  		props.put("mail.host", hostName);
94  		props.put("mail.smtp.auth", "true");
95  		props.put("mail.transport.protocol", "smtp");
96  		props.putAll(MToolKit.getSmtpProperties());
97  		Session mailSession = null;
98  
99  		if (Configuration.getBoolean("useProxy", false)) {
100 			mailSession = Session.getDefaultInstance(props, new Authenticator() {
101 				@Override
102 				public PasswordAuthentication getPasswordAuthentication() {
103 					return new PasswordAuthentication(props
104 							.getProperty("socks.proxyUserName"), props
105 							.getProperty("socks.proxyPassword"));
106 				}
107 			});
108 		} else {
109 			mailSession = Session.getDefaultInstance(props, null);
110 		}
111 
112 		mailSession.setDebug(false);
113 		try {
114 
115 			// load the keystore
116 			MimeMessage msg = new MimeMessage2(mailSession);
117 			msg.setHeader("X-Mailer", "JavaMailer");
118 			MimeMultipart mp = new MimeMultipart();
119 			MimeBodyPart bodyPart = null;
120 			MimeBodyPart bodyPartTxt = new MimeBodyPart();
121 
122 			// add the message text to the mail
123 			if (message != null) {
124 				bodyPartTxt.setContent(message.toString(),
125 						contentType == null ? DEFAULT_CONTENT_TYPE : contentType);
126 				mp.addBodyPart(bodyPartTxt);
127 			}
128 
129 			// add the attachment files
130 			if (attachments != null) {
131 				for (String attachment : attachments) {
132 					bodyPart = new MimeBodyPart();
133 					if (!new File(attachment).exists()) {
134 						throw new InternalError("File " + attachment + " does not exist");
135 					}
136 					FileDataSource fds = new FileDataSource(attachment);
137 					DataHandler dh = new DataHandler(fds);
138 					bodyPart.setFileName(attachment
139 							.substring(attachment.lastIndexOf('/') + 1));
140 					bodyPart.setDisposition(Part.ATTACHMENT);
141 					bodyPart.setDescription("File Attachment");
142 					bodyPart.setDataHandler(dh);
143 					mp.addBodyPart(bodyPart);
144 				}
145 			}
146 
147 			// add the Recipients to
148 			InternetAddress[] addresses = new InternetAddress[to.length];
149 			for (int i = 0; i < to.length; i++) {
150 				// to[i]="f-daugan@laptop2.fabdouglas.fr";
151 				addresses[i] = new InternetAddress(to[i].trim());
152 			}
153 			msg.setRecipients(Message.RecipientType.TO, addresses);
154 
155 			// add custom headers
156 			if (headers != null) {
157 				for (Header header : headers) {
158 					msg.addHeader(header.getHeaderName(), header.getHeaderValue());
159 				}
160 			}
161 
162 			msg.setFrom(new InternetAddress(from));
163 
164 			if (attachments == null || bodyPart == null) {
165 				// simple mail
166 				msg.setContent(bodyPartTxt.getContent(), bodyPartTxt.getContentType());
167 			} else {
168 				msg.setContent(mp);
169 			}
170 
171 			msg.setSubject(subject);
172 			msg.setSentDate(new java.util.Date());
173 			msg.saveChanges();
174 
175 			Transport transport = mailSession.getTransport("smtp");
176 			transport.connect(hostName, 25, userName, "");
177 			transport.sendMessage(msg, addresses);
178 			transport.close();
179 			return msg;
180 		} catch (Exception e) {
181 			e.printStackTrace();
182 		}
183 		return null;
184 	}
185 }