Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Copyright (c) 2013 Metafour International Ltd. All rights reserved.
- */
- package com.metafour.netcourier.service.impl;
- import java.io.File;
- import java.io.StringWriter;
- import java.util.Date;
- import java.util.Map;
- import java.util.Properties;
- import java.util.regex.Matcher;
- import java.util.regex.Pattern;
- import javax.mail.Message.RecipientType;
- import javax.activation.DataHandler;
- import javax.activation.DataSource;
- import javax.activation.FileDataSource;
- import javax.mail.Authenticator;
- import javax.mail.BodyPart;
- import javax.mail.Message;
- import javax.mail.MessagingException;
- import javax.mail.Multipart;
- import javax.mail.PasswordAuthentication;
- import javax.mail.Session;
- import javax.mail.Transport;
- import javax.mail.internet.InternetAddress;
- import javax.mail.internet.MimeBodyPart;
- import javax.mail.internet.MimeMessage;
- import javax.mail.internet.MimeMultipart;
- import org.apache.velocity.Template;
- import org.apache.velocity.VelocityContext;
- import org.apache.velocity.app.VelocityEngine;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Service;
- import com.metafour.netcourier.model.service.Email;
- import com.metafour.netcourier.service.AppConfig;
- import com.metafour.netcourier.service.EmailService;
- import com.metafour.netcourier.service.exception.EmailException;
- import com.metafour.util.StringsM4;
- /**
- * @author Sayeedul
- * @author Mazharul Islam
- *
- */
- @Service
- public class EmailServiceImpl implements EmailService {
- private static final Logger logger = LoggerFactory.getLogger(EmailServiceImpl.class);
- 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])*$";
- @Autowired AppConfig appConfig;
- @Override
- public boolean sendEmailMultipart(Email email) throws EmailException {
- String host = StringsM4.isNotBlank(appConfig.getMailHost())? appConfig.getMailHost() : "";
- String username = StringsM4.isNotBlank(appConfig.getMailUsername()) ? appConfig.getMailUsername() : "";
- String password = StringsM4.isNotBlank(appConfig.getMailPassword()) ? appConfig.getMailPassword() : "";
- if (host.equals("") || username.equals("") || password.equals("")){
- throw new EmailException("Insufficent user email credentials", "Insufficent user email credentials, please check netc properties");
- }
- // Properties initialization part
- Properties props = System.getProperties();
- props.put("mail.smtp.starttls.enable", "true");
- props.put("mail.smtp.host", host);
- props.setProperty("mail.transport.protocol", "smtps");
- props.put("mail.smtp.port", "465");
- props.put("mail.smtps.auth", "true");
- props.put("mail.store.protocol", "imaps");
- props.put("mail.smtp.user", username);
- props.put("mail.smtp.password", password);
- // session part
- Session session = Session.getDefaultInstance(props, null);
- MimeMessage message = new MimeMessage(session);
- try {
- // Address setting part
- InternetAddress fromAddress = new InternetAddress(username);
- message.setFrom(fromAddress);
- message.setRecipients(RecipientType.TO, InternetAddress.parse(email.getTo()));
- if (email.getCc() != null && !email.getCc().isEmpty()) {
- message.setRecipients(RecipientType.CC, InternetAddress.parse(email.getCc()));
- }
- message.setRecipients(RecipientType.BCC, InternetAddress.parse((email.getBcc() != null && !email.getBcc().isEmpty()) ? (email.getBcc() + ", ") : "" + appConfig.getMailUsername()));
- // multipart setting part
- Multipart multipart = new MimeMultipart("alternative");
- if(email.getFiles() != null && email.getFiles().size() > 0) {
- multipart = new MimeMultipart();
- }
- MimeBodyPart textPart = new MimeBodyPart();
- textPart.setText(email.getBody());
- String htmlBody = "<html>" + email.getBody() + "</html>";
- MimeBodyPart htmlPart = new MimeBodyPart();
- htmlPart.setContent(htmlBody, "text/html");
- multipart.addBodyPart(htmlPart);
- message.setContent(multipart);
- // others part
- message.setSentDate(new Date()); // Default current date
- message.setSubject(email.getSubject());
- email.setFrom(username);
- // sending email
- Transport transport = session.getTransport("smtps");
- transport.connect(host, username, password);
- transport.sendMessage(message, message.getAllRecipients());
- transport.close();
- logger.info("Email sent to " + email.getTo());
- return true;
- } catch (MessagingException e) {
- throw new EmailException(e.getMessage(), e.getCause().toString());
- }
- }
- @Override
- public boolean sendEmail(String to, String subject, String body) throws EmailException {
- return sendEmail(to, null, null, null, subject, body);
- }
- @Override
- public boolean sendEmail(String to, String replyTo, String subject, String body) throws EmailException {
- return sendEmail(to, null, null, replyTo, subject, body);
- }
- @Override
- public boolean sendEmail(String to, String cc, String bcc, String replyTo, String subject, String body) throws EmailException {
- if (StringsM4.isEmpty(to) || StringsM4.isEmpty(subject) || StringsM4.isEmpty(body)) {
- throw new EmailException("Insufficent user email credentials", "Insufficent user email credentials, please check netc properties");
- }
- Properties props = new Properties();
- props.put("mail.smtp.auth", "false");
- props.put("mail.smtp.starttls.enable", "false");
- props.put("mail.smtp.host", appConfig.getSmtpServer());
- javax.mail.Session session = javax.mail.Session.getDefaultInstance(props);
- try {
- MimeMessage msg = new MimeMessage(session);
- msg.setFrom(new InternetAddress(appConfig.getMailFrom()));
- msg.setRecipients(javax.mail.Message.RecipientType.TO, InternetAddress.parse(to));
- if (StringsM4.isNotEmpty(cc)) msg.setRecipients(javax.mail.Message.RecipientType.CC, InternetAddress.parse(cc));
- if (StringsM4.isNotEmpty(bcc)) msg.setRecipients(javax.mail.Message.RecipientType.BCC, InternetAddress.parse(bcc));
- if (StringsM4.isNotEmpty(replyTo)) msg.setReplyTo(InternetAddress.parse(replyTo));
- msg.setSubject(subject);
- msg.setContent(body, "text/html;charset=UTF-8");
- Transport.send(msg);
- logger.info("Task mail sent to: {} , subject = {}", to, subject);
- return true;
- } catch (Exception e) {
- logger.error("Task mail sending failed" + e.getMessage(), e);
- throw new EmailException("Failed to process email", e.toString());
- }
- }
- @Override
- public boolean validate(String emails) {
- if (StringsM4.isBlank(emails)) return false;
- emails = emails.indexOf(';') != -1 ? emails.replace(';' , ',') : emails;
- Pattern pattern = Pattern.compile(EMAIL_REGEX);
- String[] emailsArr = emails.split(",");
- for (String eml : emailsArr) {
- if (StringsM4.isBlank(eml)) continue;
- Matcher matcher = pattern.matcher(eml);
- if (!matcher.matches()) return false;
- }
- return true;
- }
- @Override
- public boolean sendEmailMultipartWithVelocityTemplate(Email email, String vmTemplate, Map<String, String> context) throws EmailException {
- String host = StringsM4.isNotBlank(appConfig.getMailHost())? appConfig.getMailHost() : "";
- String username = StringsM4.isNotBlank(appConfig.getMailUsername()) ? appConfig.getMailUsername() : "";
- String password = StringsM4.isNotBlank(appConfig.getMailPassword()) ? appConfig.getMailPassword() : "";
- if (host.equals("") || username.equals("") || password.equals("")){
- throw new EmailException("Insufficent user email credentials", "Insufficent user email credentials, please check netc properties");
- }
- if(logger.isDebugEnabled()) logger.debug("Host {} , username {}", host, username);
- // Properties initialization part
- Properties props = System.getProperties();
- props.put("mail.smtp.auth", "true");
- props.put("mail.smtp.starttls.enable", "true");
- props.put("mail.smtp.host", host);
- props.put("mail.smtp.port", "587");
- // session part
- Session session = Session.getInstance(props, new Authenticator() {
- @Override
- protected PasswordAuthentication getPasswordAuthentication() {
- return new PasswordAuthentication(username, password);
- }
- });
- // Creating default MIME message object
- MimeMessage message = new MimeMessage(session);
- try {
- message.setFrom(new InternetAddress(username));
- message.addRecipient(Message.RecipientType.TO, new InternetAddress(email.getTo()));
- message.setSubject(email.getSubject());
- BodyPart body = new MimeBodyPart();
- // velocity stuff.
- // Initialize velocity
- VelocityEngine velocityEngine = new VelocityEngine();
- velocityEngine.init();
- Template template = velocityEngine.getTemplate(vmTemplate);
- // create context and add data
- VelocityContext velocityContext = new VelocityContext();
- for(Map.Entry<String, String> c : context.entrySet()) {
- velocityContext.put(c.getKey(), c.getValue());
- }
- /* now render the template into a StringWriter */
- StringWriter out = new StringWriter();
- template.merge(velocityContext, out);
- // velocity stuff end
- body.setContent(out.toString(), "text/html");
- //set Multipart
- Multipart multipart = new MimeMultipart();
- multipart.addBodyPart(body);
- if(!email.getFiles().isEmpty()) {
- for(String attachFile : email.getFiles()) {
- body = new MimeBodyPart();
- if(logger.isDebugEnabled()) logger.debug("Avsolute path of file: {}", attachFile);
- DataSource source = new FileDataSource(attachFile);
- body.setDataHandler(new DataHandler(source));
- body.setFileName(attachFile.substring(attachFile.lastIndexOf(File.separator) + 1));
- multipart.addBodyPart(body);
- }
- }
- message.setContent(multipart);
- // send mail
- Transport.send(message);
- return true;
- } catch (MessagingException e) {
- throw new EmailException(e.getMessage(), e.getCause().toString());
- }
- }
- }
Add Comment
Please, Sign In to add comment