Guest User

Untitled

a guest
Mar 12th, 2018
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 9.67 KB | None | 0 0
  1. /**
  2. * Copyright (c) 2013 Metafour International Ltd. All rights reserved.
  3. */
  4. package com.metafour.netcourier.service.impl;
  5.  
  6. import java.io.File;
  7. import java.io.StringWriter;
  8. import java.util.Date;
  9. import java.util.Map;
  10. import java.util.Properties;
  11. import java.util.regex.Matcher;
  12. import java.util.regex.Pattern;
  13.  
  14. import javax.mail.Message.RecipientType;
  15. import javax.activation.DataHandler;
  16. import javax.activation.DataSource;
  17. import javax.activation.FileDataSource;
  18. import javax.mail.Authenticator;
  19. import javax.mail.BodyPart;
  20. import javax.mail.Message;
  21. import javax.mail.MessagingException;
  22. import javax.mail.Multipart;
  23. import javax.mail.PasswordAuthentication;
  24. import javax.mail.Session;
  25. import javax.mail.Transport;
  26. import javax.mail.internet.InternetAddress;
  27. import javax.mail.internet.MimeBodyPart;
  28. import javax.mail.internet.MimeMessage;
  29. import javax.mail.internet.MimeMultipart;
  30.  
  31. import org.apache.velocity.Template;
  32. import org.apache.velocity.VelocityContext;
  33. import org.apache.velocity.app.VelocityEngine;
  34. import org.slf4j.Logger;
  35. import org.slf4j.LoggerFactory;
  36. import org.springframework.beans.factory.annotation.Autowired;
  37. import org.springframework.stereotype.Service;
  38.  
  39. import com.metafour.netcourier.model.service.Email;
  40. import com.metafour.netcourier.service.AppConfig;
  41. import com.metafour.netcourier.service.EmailService;
  42. import com.metafour.netcourier.service.exception.EmailException;
  43. import com.metafour.util.StringsM4;
  44.  
  45. /**
  46. * @author Sayeedul
  47. * @author Mazharul Islam
  48. *
  49. */
  50. @Service
  51. public class EmailServiceImpl implements EmailService {
  52. private static final Logger logger = LoggerFactory.getLogger(EmailServiceImpl.class);
  53. private static final String EMAIL_REGEX = "^[a-zA-Z0-9_!#$%&.*+/=?`{|}~^-]+(?:\\.[a-zA-Z0-9_!#$%&.*+/=?`{|}~^-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\\.)+(?!web)[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])*$";
  54.  
  55. @Autowired AppConfig appConfig;
  56.  
  57. @Override
  58. public boolean sendEmailMultipart(Email email) throws EmailException {
  59.  
  60. String host = StringsM4.isNotBlank(appConfig.getMailHost())? appConfig.getMailHost() : "";
  61. String username = StringsM4.isNotBlank(appConfig.getMailUsername()) ? appConfig.getMailUsername() : "";
  62. String password = StringsM4.isNotBlank(appConfig.getMailPassword()) ? appConfig.getMailPassword() : "";
  63. if (host.equals("") || username.equals("") || password.equals("")){
  64. throw new EmailException("Insufficent user email credentials", "Insufficent user email credentials, please check netc properties");
  65. }
  66.  
  67. // Properties initialization part
  68. Properties props = System.getProperties();
  69. props.put("mail.smtp.starttls.enable", "true");
  70. props.put("mail.smtp.host", host);
  71. props.setProperty("mail.transport.protocol", "smtps");
  72. props.put("mail.smtp.port", "465");
  73. props.put("mail.smtps.auth", "true");
  74. props.put("mail.store.protocol", "imaps");
  75. props.put("mail.smtp.user", username);
  76. props.put("mail.smtp.password", password);
  77.  
  78. // session part
  79. Session session = Session.getDefaultInstance(props, null);
  80. MimeMessage message = new MimeMessage(session);
  81. try {
  82. // Address setting part
  83. InternetAddress fromAddress = new InternetAddress(username);
  84. message.setFrom(fromAddress);
  85. message.setRecipients(RecipientType.TO, InternetAddress.parse(email.getTo()));
  86. if (email.getCc() != null && !email.getCc().isEmpty()) {
  87. message.setRecipients(RecipientType.CC, InternetAddress.parse(email.getCc()));
  88. }
  89. message.setRecipients(RecipientType.BCC, InternetAddress.parse((email.getBcc() != null && !email.getBcc().isEmpty()) ? (email.getBcc() + ", ") : "" + appConfig.getMailUsername()));
  90.  
  91. // multipart setting part
  92. Multipart multipart = new MimeMultipart("alternative");
  93. if(email.getFiles() != null && email.getFiles().size() > 0) {
  94. multipart = new MimeMultipart();
  95. }
  96.  
  97. MimeBodyPart textPart = new MimeBodyPart();
  98. textPart.setText(email.getBody());
  99. String htmlBody = "<html>" + email.getBody() + "</html>";
  100. MimeBodyPart htmlPart = new MimeBodyPart();
  101. htmlPart.setContent(htmlBody, "text/html");
  102. multipart.addBodyPart(htmlPart);
  103. message.setContent(multipart);
  104.  
  105. // others part
  106. message.setSentDate(new Date()); // Default current date
  107. message.setSubject(email.getSubject());
  108. email.setFrom(username);
  109.  
  110. // sending email
  111. Transport transport = session.getTransport("smtps");
  112. transport.connect(host, username, password);
  113. transport.sendMessage(message, message.getAllRecipients());
  114. transport.close();
  115.  
  116. logger.info("Email sent to " + email.getTo());
  117. return true;
  118. } catch (MessagingException e) {
  119. throw new EmailException(e.getMessage(), e.getCause().toString());
  120. }
  121. }
  122.  
  123. @Override
  124. public boolean sendEmail(String to, String subject, String body) throws EmailException {
  125. return sendEmail(to, null, null, null, subject, body);
  126. }
  127.  
  128. @Override
  129. public boolean sendEmail(String to, String replyTo, String subject, String body) throws EmailException {
  130. return sendEmail(to, null, null, replyTo, subject, body);
  131. }
  132.  
  133. @Override
  134. public boolean sendEmail(String to, String cc, String bcc, String replyTo, String subject, String body) throws EmailException {
  135. if (StringsM4.isEmpty(to) || StringsM4.isEmpty(subject) || StringsM4.isEmpty(body)) {
  136. throw new EmailException("Insufficent user email credentials", "Insufficent user email credentials, please check netc properties");
  137. }
  138. Properties props = new Properties();
  139. props.put("mail.smtp.auth", "false");
  140. props.put("mail.smtp.starttls.enable", "false");
  141. props.put("mail.smtp.host", appConfig.getSmtpServer());
  142. javax.mail.Session session = javax.mail.Session.getDefaultInstance(props);
  143. try {
  144. MimeMessage msg = new MimeMessage(session);
  145. msg.setFrom(new InternetAddress(appConfig.getMailFrom()));
  146. msg.setRecipients(javax.mail.Message.RecipientType.TO, InternetAddress.parse(to));
  147. if (StringsM4.isNotEmpty(cc)) msg.setRecipients(javax.mail.Message.RecipientType.CC, InternetAddress.parse(cc));
  148. if (StringsM4.isNotEmpty(bcc)) msg.setRecipients(javax.mail.Message.RecipientType.BCC, InternetAddress.parse(bcc));
  149. if (StringsM4.isNotEmpty(replyTo)) msg.setReplyTo(InternetAddress.parse(replyTo));
  150. msg.setSubject(subject);
  151. msg.setContent(body, "text/html;charset=UTF-8");
  152. Transport.send(msg);
  153. logger.info("Task mail sent to: {} , subject = {}", to, subject);
  154. return true;
  155. } catch (Exception e) {
  156. logger.error("Task mail sending failed" + e.getMessage(), e);
  157. throw new EmailException("Failed to process email", e.toString());
  158. }
  159. }
  160.  
  161. @Override
  162. public boolean validate(String emails) {
  163. if (StringsM4.isBlank(emails)) return false;
  164. emails = emails.indexOf(';') != -1 ? emails.replace(';' , ',') : emails;
  165. Pattern pattern = Pattern.compile(EMAIL_REGEX);
  166. String[] emailsArr = emails.split(",");
  167. for (String eml : emailsArr) {
  168. if (StringsM4.isBlank(eml)) continue;
  169. Matcher matcher = pattern.matcher(eml);
  170. if (!matcher.matches()) return false;
  171. }
  172. return true;
  173. }
  174.  
  175. @Override
  176. public boolean sendEmailMultipartWithVelocityTemplate(Email email, String vmTemplate, Map<String, String> context) throws EmailException {
  177. String host = StringsM4.isNotBlank(appConfig.getMailHost())? appConfig.getMailHost() : "";
  178. String username = StringsM4.isNotBlank(appConfig.getMailUsername()) ? appConfig.getMailUsername() : "";
  179. String password = StringsM4.isNotBlank(appConfig.getMailPassword()) ? appConfig.getMailPassword() : "";
  180. if (host.equals("") || username.equals("") || password.equals("")){
  181. throw new EmailException("Insufficent user email credentials", "Insufficent user email credentials, please check netc properties");
  182. }
  183.  
  184. if(logger.isDebugEnabled()) logger.debug("Host {} , username {}", host, username);
  185.  
  186. // Properties initialization part
  187. Properties props = System.getProperties();
  188. props.put("mail.smtp.auth", "true");
  189. props.put("mail.smtp.starttls.enable", "true");
  190. props.put("mail.smtp.host", host);
  191. props.put("mail.smtp.port", "587");
  192.  
  193. // session part
  194. Session session = Session.getInstance(props, new Authenticator() {
  195. @Override
  196. protected PasswordAuthentication getPasswordAuthentication() {
  197. return new PasswordAuthentication(username, password);
  198. }
  199. });
  200.  
  201.  
  202. // Creating default MIME message object
  203. MimeMessage message = new MimeMessage(session);
  204. try {
  205. message.setFrom(new InternetAddress(username));
  206. message.addRecipient(Message.RecipientType.TO, new InternetAddress(email.getTo()));
  207. message.setSubject(email.getSubject());
  208.  
  209. BodyPart body = new MimeBodyPart();
  210.  
  211. // velocity stuff.
  212. // Initialize velocity
  213. VelocityEngine velocityEngine = new VelocityEngine();
  214. velocityEngine.init();
  215.  
  216. Template template = velocityEngine.getTemplate(vmTemplate);
  217.  
  218. // create context and add data
  219. VelocityContext velocityContext = new VelocityContext();
  220. for(Map.Entry<String, String> c : context.entrySet()) {
  221. velocityContext.put(c.getKey(), c.getValue());
  222. }
  223.  
  224. /* now render the template into a StringWriter */
  225. StringWriter out = new StringWriter();
  226. template.merge(velocityContext, out);
  227.  
  228. // velocity stuff end
  229. body.setContent(out.toString(), "text/html");
  230.  
  231. //set Multipart
  232. Multipart multipart = new MimeMultipart();
  233. multipart.addBodyPart(body);
  234.  
  235. if(!email.getFiles().isEmpty()) {
  236. for(String attachFile : email.getFiles()) {
  237. body = new MimeBodyPart();
  238. if(logger.isDebugEnabled()) logger.debug("Avsolute path of file: {}", attachFile);
  239. DataSource source = new FileDataSource(attachFile);
  240. body.setDataHandler(new DataHandler(source));
  241. body.setFileName(attachFile.substring(attachFile.lastIndexOf(File.separator) + 1));
  242. multipart.addBodyPart(body);
  243. }
  244. }
  245.  
  246. message.setContent(multipart);
  247.  
  248. // send mail
  249. Transport.send(message);
  250.  
  251. return true;
  252. } catch (MessagingException e) {
  253. throw new EmailException(e.getMessage(), e.getCause().toString());
  254. }
  255. }
  256.  
  257. }
Add Comment
Please, Sign In to add comment