PageRenderTime 12ms CodeModel.GetById 1ms RepoModel.GetById 0ms app.codeStats 0ms

/src/mpv5/mail/SimpleMail.java

http://mp-rechnungs-und-kundenverwaltung.googlecode.com/
Java | 530 lines | 323 code | 60 blank | 147 comment | 26 complexity | 15a2e6ecb54a5d363271044ffb8d187b MD5 | raw file
Possible License(s): LGPL-3.0, Apache-2.0, GPL-3.0, GPL-2.0, AGPL-3.0, JSON, BSD-3-Clause
  1. /*
  2. * This file is part of YaBS.
  3. *
  4. * YaBS is free software: you can redistribute it and/or modify
  5. * it under the terms of the GNU General Public License as published by
  6. * the Free Software Foundation, either version 3 of the License, or
  7. * (at your option) any later version.
  8. *
  9. * YaBS is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with YaBS. If not, see <http://www.gnu.org/licenses/>.
  16. */
  17. package mpv5.mail;
  18. import com.sun.mail.smtp.SMTPSSLTransport;
  19. import java.io.File;
  20. import java.util.ArrayList;
  21. import java.util.List;
  22. import java.util.Properties;
  23. import javax.activation.DataHandler;
  24. import javax.activation.DataSource;
  25. import javax.activation.FileDataSource;
  26. import javax.mail.Authenticator;
  27. import javax.mail.Message;
  28. import javax.mail.MessagingException;
  29. import javax.mail.Multipart;
  30. import javax.mail.NoSuchProviderException;
  31. import javax.mail.PasswordAuthentication;
  32. import javax.mail.Session;
  33. import javax.mail.Transport;
  34. import javax.mail.internet.InternetAddress;
  35. import javax.mail.internet.MimeBodyPart;
  36. import javax.mail.internet.MimeMessage;
  37. import javax.mail.internet.MimeMultipart;
  38. import mpv5.globals.Messages;
  39. import mpv5.logging.Log;
  40. import mpv5.ui.dialogs.Notificator;
  41. import mpv5.ui.dialogs.Popup;
  42. import mpv5.utils.export.Export;
  43. import mpv5.utils.jobs.Waiter;
  44. /**
  45. * A simple mail implementation, taken from
  46. * http://www.tutorials.de/forum/java/255387-email-mit-javamail-versenden.html
  47. *
  48. */
  49. public class SimpleMail implements Waiter {
  50. private String smtpHost = "";
  51. private String username = "";
  52. private String password = "";
  53. private String senderAddress = "";
  54. private String recipientsAddress = "";
  55. private String subject = "";
  56. private String text = "";
  57. private String bccAddress = null;
  58. private List<String> cc = new ArrayList<String>();
  59. private List<String> bcc = new ArrayList<String>();
  60. private List<String> rec = new ArrayList<String>();
  61. private boolean useTls;
  62. private boolean useSmtps;
  63. private File attachment;
  64. private String ccAddress;
  65. /**
  66. *
  67. * @param smtpHost
  68. * @param username
  69. * @param password
  70. * @param senderAddress
  71. * @param recipientsAddress
  72. * @param subject
  73. * @param text
  74. * @throws MessagingException
  75. */
  76. public SimpleMail(String smtpHost, String username, String password, String senderAddress, String recipientsAddress, String subject, String text) throws MessagingException {
  77. this.smtpHost = smtpHost;
  78. this.username = username;
  79. this.password = password;
  80. this.senderAddress = senderAddress;
  81. this.recipientsAddress = recipientsAddress;
  82. this.subject = subject;
  83. this.text = text;
  84. }
  85. public SimpleMail() {
  86. }
  87. /**
  88. * @author Sateesh Rudrangi
  89. * @param smtpHost
  90. * @param username
  91. * @param password
  92. * @param from
  93. * @param recipientsAddress
  94. * @param subject
  95. * @param text
  96. * @param attachment
  97. * @throws MessagingException
  98. */
  99. private void sendMail() {
  100. Runnable runnable = new Runnable() {
  101. @Override
  102. public void run() {
  103. if (!useSmtps) {
  104. try {
  105. sendSmptmail();
  106. } catch (MessagingException ex) {
  107. Log.Debug(ex);
  108. }
  109. } else {
  110. try {
  111. sendSmptsMail();
  112. } catch (NoSuchProviderException ex) {
  113. Log.Debug(ex);
  114. } catch (MessagingException ex) {
  115. Log.Debug(ex);
  116. }
  117. }
  118. }
  119. };
  120. new Thread(runnable).start();
  121. }
  122. @Override
  123. public void set(Object object, Exception exception) throws Exception {
  124. if (exception == null) {
  125. try {
  126. if (object instanceof Export) {
  127. setAttachment(((Export) object).getTargetFile());
  128. sendMail();
  129. } else {
  130. setAttachment((File) object);
  131. sendMail();
  132. }
  133. } catch (Exception e) {
  134. throw e;
  135. } finally {
  136. }
  137. } else {
  138. throw exception;
  139. }
  140. }
  141. /**
  142. * Set the configuration for mails
  143. * @param c
  144. * @throws UnsupportedOperationException
  145. */
  146. public void setMailConfiguration(MailConfiguration c) throws UnsupportedOperationException {
  147. if (c != null) {
  148. setPassword(c.getPassword());
  149. setSenderAddress(c.getSenderAddress());
  150. setSmtpHost(c.getSmtpHost());
  151. setUsername(c.getUsername());
  152. setUseTls(c.isUseTls());
  153. setUseSmtps(c.isUseSmtps());
  154. } else {
  155. throw new UnsupportedOperationException("MailConfig cannot be null!");
  156. }
  157. }
  158. /**
  159. * @return the smtpHost
  160. */
  161. public String getSmtpHost() {
  162. return smtpHost;
  163. }
  164. /**
  165. * @param smtpHost the smtpHost to set
  166. */
  167. public void setSmtpHost(String smtpHost) {
  168. this.smtpHost = smtpHost;
  169. }
  170. /**
  171. * @return the username
  172. */
  173. public String getUsername() {
  174. return username;
  175. }
  176. /**
  177. * @param username the username to set
  178. */
  179. public void setUsername(String username) {
  180. this.username = username;
  181. }
  182. /**
  183. * @return the password
  184. */
  185. public String getPassword() {
  186. return password;
  187. }
  188. /**
  189. * @param password the password to set
  190. */
  191. public void setPassword(String password) {
  192. this.password = password;
  193. }
  194. /**
  195. * @return the senderAddress
  196. */
  197. public String getSenderAddress() {
  198. return senderAddress;
  199. }
  200. /**
  201. * @param senderAddress the senderAddress to set
  202. */
  203. public void setSenderAddress(String senderAddress) {
  204. this.senderAddress = senderAddress;
  205. }
  206. /**
  207. * @return the recipientsAddress
  208. */
  209. public String getRecipientsAddress() {
  210. return recipientsAddress;
  211. }
  212. /**
  213. * @param recipientsAddress the recipientsAddress to set
  214. */
  215. public void setRecipientsAddress(String recipientsAddress) {
  216. this.recipientsAddress = recipientsAddress;
  217. String[] ccs = recipientsAddress.split(";");
  218. for (int i = 0; i < ccs.length; i++) {
  219. String ccc = ccs[i];
  220. addAddress(ccc);
  221. }
  222. }
  223. /**
  224. * @return the subject
  225. */
  226. public String getSubject() {
  227. return subject;
  228. }
  229. /**
  230. * @param subject the subject to set
  231. */
  232. public void setSubject(String subject) {
  233. this.subject = subject;
  234. }
  235. /**
  236. * @return the text
  237. */
  238. public String getText() {
  239. return text;
  240. }
  241. /**
  242. * @param text the text to set
  243. */
  244. public void setText(String text) {
  245. this.text = text;
  246. }
  247. /**
  248. * @return the attachment
  249. */
  250. public File getAttachment() {
  251. return attachment;
  252. }
  253. /**
  254. * @param attachment the attachment to set
  255. */
  256. public void setAttachment(File attachment) {
  257. this.attachment = attachment;
  258. }
  259. /**
  260. * @return the useTls
  261. */
  262. public boolean isUseTls() {
  263. return useTls;
  264. }
  265. /**
  266. * @param useTls the useTls to set
  267. */
  268. public void setUseTls(boolean useTls) {
  269. this.useTls = useTls;
  270. }
  271. /**
  272. * @return the useSmtps
  273. */
  274. public boolean isUseSmtps() {
  275. return useSmtps;
  276. }
  277. /**
  278. * @param useSmtps the useSmtps to set
  279. */
  280. public void setUseSmtps(boolean useSmtps) {
  281. this.useSmtps = useSmtps;
  282. }
  283. private void sendSmptmail() throws MessagingException {
  284. Log.Debug(this, "Sending mail via SMTP");
  285. mpv5.YabsViewProxy.instance().getProgressbar().setIndeterminate(true);
  286. MailAuthenticator auth = new MailAuthenticator(username, password);
  287. Properties properties = null;
  288. Session session = null;
  289. properties = new Properties();
  290. properties.put("mail.smtp.host", smtpHost);
  291. if (username != null) {
  292. properties.put("mail.smtp.auth", "true");
  293. }
  294. if (useTls) {
  295. properties.put("mail.smtp.starttls.enable", "true");
  296. }
  297. session = Session.getDefaultInstance(properties, auth);
  298. // Define message
  299. MimeMessage message = new MimeMessage(session);
  300. message.setFrom(new InternetAddress(senderAddress));
  301. message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipientsAddress));
  302. if (getBccAddress() != null) {
  303. message.addRecipient(Message.RecipientType.BCC, new InternetAddress(bccAddress));
  304. }
  305. message.setSubject(subject);
  306. // create the message part
  307. MimeBodyPart messageBodyPart = new MimeBodyPart();
  308. //fill message
  309. messageBodyPart.setText(text);
  310. Multipart multipart = new MimeMultipart();
  311. multipart.addBodyPart(messageBodyPart);
  312. if (attachment != null) {
  313. // Part two is attachment
  314. messageBodyPart = new MimeBodyPart();
  315. DataSource source = new FileDataSource(attachment);
  316. messageBodyPart.setDataHandler(new DataHandler(source));
  317. messageBodyPart.setFileName(attachment.getName());
  318. multipart.addBodyPart(messageBodyPart);
  319. }
  320. // Put parts in message
  321. message.setContent(multipart);
  322. try {
  323. // Send the message
  324. Transport.send(message);
  325. mpv5.YabsViewProxy.instance().getProgressbar().setIndeterminate(false);
  326. Log.Debug(this, "Mail sent: " + message);
  327. Popup.notice(Messages.MAIL_SENT + " " + recipientsAddress);
  328. } catch (MessagingException messagingException) {
  329. Popup.error(messagingException);
  330. Log.Debug(this, messagingException.getLocalizedMessage());
  331. } finally {
  332. // close the connection
  333. }
  334. }
  335. /**
  336. * From http://www.nepherte.be/send-mail-over-smtps-in-java/
  337. * @throws NoSuchProviderException
  338. * @throws MessagingException
  339. */
  340. private void sendSmptsMail() throws NoSuchProviderException, MessagingException {
  341. mpv5.YabsViewProxy.instance().getProgressbar().setIndeterminate(true);
  342. Log.Debug(this, "Sending mail via SMTPS");
  343. // create properties
  344. Properties props = System.getProperties();
  345. MailAuthenticator auth = new MailAuthenticator(username, password);
  346. props.put("mail.smtps.auth", Boolean.toString(username != null));
  347. props.put("mail.smtps.starttls.enable", Boolean.toString(useTls));
  348. // < -- it is important you use the correct port. smtp uses 25, smtps 465 -->
  349. props.put("mail.smtps.port", "465");
  350. // < -- put the smtps server host address here -->
  351. props.put("mail.smtps.host", smtpHost);
  352. //
  353. // props.put("mail.smtp.port", "587");
  354. // props.put("mail.smtp.auth", (username != null));
  355. // props.put("mail.smtp.starttls.enable", useTls);
  356. // create session
  357. Session session = Session.getDefaultInstance(props, auth);
  358. // session.setDebug(true);
  359. // Define message
  360. MimeMessage message = new MimeMessage(session);
  361. message.setFrom(new InternetAddress(senderAddress));
  362. for (int i = 0; i < rec.size(); i++) {
  363. String recc = rec.get(i);
  364. try {
  365. message.addRecipient(Message.RecipientType.TO, new InternetAddress(recc));
  366. } catch (MessagingException messagingException) {
  367. Notificator.raiseNotification(messagingException);
  368. }
  369. }
  370. for (int i = 0; i < bcc.size(); i++) {
  371. String bbc = bcc.get(i);
  372. try {
  373. message.addRecipient(Message.RecipientType.BCC, new InternetAddress(bbc));
  374. } catch (MessagingException messagingException) {
  375. Notificator.raiseNotification(messagingException);
  376. }
  377. }
  378. for (int i = 0; i < cc.size(); i++) {
  379. String ccc = cc.get(i);
  380. try {
  381. message.addRecipient(Message.RecipientType.CC, new InternetAddress(ccc));
  382. } catch (MessagingException messagingException) {
  383. Notificator.raiseNotification(messagingException);
  384. }
  385. }
  386. message.setSubject(subject);
  387. // create the message part
  388. MimeBodyPart messageBodyPart = new MimeBodyPart();
  389. //fill message
  390. messageBodyPart.setText(text);
  391. Multipart multipart = new MimeMultipart();
  392. multipart.addBodyPart(messageBodyPart);
  393. if (attachment != null) {
  394. // Part two is attachment
  395. messageBodyPart = new MimeBodyPart();
  396. DataSource source = new FileDataSource(attachment);
  397. messageBodyPart.setDataHandler(new DataHandler(source));
  398. messageBodyPart.setFileName(attachment.getName());
  399. multipart.addBodyPart(messageBodyPart);
  400. }
  401. // Put parts in message
  402. message.setContent(multipart);
  403. message.saveChanges();
  404. // transport the message
  405. // < -- we will send the message over smtps -->
  406. SMTPSSLTransport transport = (SMTPSSLTransport) session.getTransport("smtps");
  407. // connect to server
  408. try {
  409. // < -- fill in email address and password -->
  410. transport.connect();
  411. // send the message
  412. transport.sendMessage(message, message.getAllRecipients());
  413. mpv5.YabsViewProxy.instance().getProgressbar().setIndeterminate(false);
  414. Log.Debug(this, "Mail sent: " + message);
  415. Popup.notice(Messages.MAIL_SENT + " " + recipientsAddress);
  416. } catch (MessagingException messagingException) {
  417. Popup.error(messagingException);
  418. Log.Debug(this, messagingException.getLocalizedMessage());
  419. } finally {
  420. // close the connection
  421. transport.close();
  422. }
  423. }
  424. /**
  425. * @return the bccAddress
  426. */
  427. public String getBccAddress() {
  428. return bccAddress;
  429. }
  430. /**
  431. * @param bccAddress the bccAddress to set
  432. */
  433. public void setBccAddress(String bccAddress) {
  434. this.bccAddress = bccAddress;
  435. String[] ccs = bccAddress.split(";");
  436. for (int i = 0; i < ccs.length; i++) {
  437. String ccc = ccs[i];
  438. addBCCAddress(ccc);
  439. }
  440. }
  441. public void addCCAddress(String ccc) {
  442. cc.add(ccc);
  443. }
  444. public void setCCAddress(String cc) {
  445. this.ccAddress = cc;
  446. String[] ccs = cc.split(";");
  447. for (int i = 0; i < ccs.length; i++) {
  448. String ccc = ccs[i];
  449. addCCAddress(ccc);
  450. }
  451. }
  452. private void addAddress(String ccc) {
  453. rec.add(ccc);
  454. }
  455. private void addBCCAddress(String ccc) {
  456. bcc.add(ccc);
  457. }
  458. class MailAuthenticator extends Authenticator {
  459. private final String user;
  460. private final String password;
  461. public MailAuthenticator(String user, String password) {
  462. this.user = user;
  463. this.password = password;
  464. }
  465. @Override
  466. protected PasswordAuthentication getPasswordAuthentication() {
  467. return new PasswordAuthentication(this.user, this.password);
  468. }
  469. }
  470. }