All Downloads are FREE. Search and download functionalities are using the official Maven repository.

nosi.core.mail.EmailMessage Maven / Gradle / Ivy

Go to download

IGRP Framework is a powerful and highly customizable platform developed by the Operational Nucleus for the Information Society (NOSi) to create web applications, it provides out of box, several modules to make easy to create stand-alone, production-grade web applications: authentication and access-control, business processes automation, reporting, page builder with automatic code generation and incorporation of the Once-Only-Principle, written in Java. IGRP Framework WAR - Contains some keys resources that give UI to IGRP Framework and others supports files.

There is a newer version: 2.0.0.240912-RCM
Show newest version
package nosi.core.mail;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import jakarta.activation.DataHandler;
import jakarta.mail.Message;
import jakarta.mail.MessagingException;
import jakarta.mail.Multipart;
import jakarta.mail.PasswordAuthentication;
import jakarta.mail.Session;
import jakarta.mail.Transport;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeBodyPart;
import jakarta.mail.internet.MimeMessage;
import jakarta.mail.internet.MimeMultipart;
import jakarta.mail.util.ByteArrayDataSource;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import nosi.core.config.ConfigApp;

/**
 * Iekiny Marcel
 * Dec 12, 2017
 */
public class EmailMessage { 
	
	private static final Logger LOG = LogManager.getLogger(EmailMessage.class); 
	
	public static final String EMAIL_REGEXP = "[a-zA-Z0-9!#$%&\\'*+\\/=?^_`{|}~-]+(?:\\.[a-zA-Z0-9!#$%&\'*+\\/=?^_`{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?"; 

	private String to;
	private String cc;
	private String bcc;
	private String from;
	private String subject;
	private String msg;
	
	private boolean multipleRecipients;
	
	private String replyTo; // emails separated by comma 
	
	private String charset;
	private String subType;
	
	private Properties settings;
	
	// credentials 
	private String auth_username;
	private String auth_password;
	
	private List attaches; 
	private List attachesBytes; 
	
	private EmailMessage() { 
		if(!this.load()) 
			this.loadDefaultConfig();
		this.attaches = new ArrayList<>();
		this.attachesBytes = new ArrayList<>();
		this.multipleRecipients = false;
	}
	
	public static EmailMessage newInstance() {	
		return new EmailMessage();
	}
	
	public void loadDefaultConfig() {
		System.setProperty("java.net.preferIPv4Stack", "true");
		// Get system properties
		Properties properties = System.getProperties();
		// Setup mail server
		properties.put("mail.smtp.host", "smtp.gmail.com");
		properties.put("mail.smtp.socketFactory.port", "465");
		properties.put("mail.smtp.socketFactory.class","jakarta.net.ssl.SSLSocketFactory");
		properties.put("mail.smtp.auth", "true");
		properties.put("mail.smtp.port", "465");
		properties.put("mail.smtp.ssl.checkserveridentity", true); // Compliant
		this.settings = new Properties(properties);
	}
	
	public EmailMessage setTo(String to) {
		this.to = to.replace(";", ",");
		return this;
	}

	public EmailMessage setFrom(String from) {
		this.from = from;
		return this;
	}

	public EmailMessage setSubject(String subject) {
		this.subject = subject;
		return this;
	}

	public EmailMessage setMsg(String msg) {
		this.msg = msg;
		return this;
	}
	
	public EmailMessage setMsg(String msg, String charset) {
		this.msg = msg;
		this.charset = charset;
		return this;
	}
	
	public EmailMessage setMsg(String msg, String charset, String subType) {
		this.msg = msg;
		this.charset = charset;
		this.subType = subType;
		return this;
	}
	
	public EmailMessage attach(File attach) {
		this.attaches.add(attach);
		return this;
	}
	
	public EmailMessage attach(Attachment attach) {
		this.attachesBytes.add(attach);
		return this;
	}
	
	public EmailMessage newSettings(Properties p) {
		this.settings = p;
		return this;
	}
	
	public Properties getSettings() {
		return this.settings;
	}
	
	public EmailMessage authenticate(String username, String password) {
		this.auth_username = username;
		this.auth_password = password;
		return this;
	}
	
	private void checkNSetupCredencials() {
		if(auth_username == null || auth_username.isEmpty() || auth_password == null || auth_password.isEmpty()) {
			auth_username = settings.getProperty("mail.user"); 
			auth_password = settings.getProperty("mail.password"); 
		}
	}
	
	private boolean load() {
		settings = ConfigApp.getInstance().getMainSettings(); 
		return !settings.isEmpty();
	}
	
	public boolean send() throws IOException { 
		try{
			checkNSetupCredencials();
			// Get the default Session object.
			Session session = Session.getInstance(this.settings,
				new jakarta.mail.Authenticator() {
					protected PasswordAuthentication getPasswordAuthentication() {
						return new PasswordAuthentication(auth_username, auth_password);
					}
			});
			// Create a default MimeMessage object. 
			MimeMessage message = new MimeMessage(session); 
			if(!validateEmail(this.from)) {
				LOG.error("Email not sent ... Invalid email (from): <" + this.from + "> ");
				return false;
			}
			// Set From: header field of the header.
			message.setFrom(new InternetAddress(this.from));
			// Set To: header field of the header. 
			if(this.multipleRecipients) {
				if(!validateEmails(this.to)) {
					LOG.error("Email not sent (To)... one of email is invalid: <" + this.to + "> ");
					return false;
				}
				message.addRecipients(Message.RecipientType.CC,InternetAddress.parse(this.to)); // this.to is a string separated by comma 
			}else {
				if(!validateEmails(this.to)) {
					LOG.error("Email not sent (To)... one of email is invalid: <" + this.to + "> ");
					return false;
				}		
				if(this.to != null && !this.to.isEmpty()) 
					message.addRecipients(Message.RecipientType.TO,InternetAddress.parse(this.to)); 
			}			
			if(this.cc != null && !this.cc.isEmpty())	
				message.addRecipients(Message.RecipientType.CC,InternetAddress.parse(this.cc));
			if(this.bcc != null && !this.bcc.isEmpty()) 
				message.addRecipients(Message.RecipientType.BCC,InternetAddress.parse(this.bcc));
			if(this.replyTo != null && !this.replyTo.isEmpty() && validateEmails(this.replyTo)) 
				message.setReplyTo(InternetAddress.parse(this.replyTo));
			// Set Subject: header field
			message.setSubject(this.subject); 
			// If there is any attach ... 
			if(!this.attaches.isEmpty() || !this.attachesBytes.isEmpty()) {
				// Create a multipart message 
				MimeBodyPart mbp = new MimeBodyPart();
		        Multipart multipart = new MimeMultipart();
			    // Now set the actual message 
				if(this.charset != null && !this.charset.isEmpty() && this.subType != null && !this.subType.isEmpty())
					mbp.setText(this.msg, this.charset, this.subType);
				else if(this.charset != null && !this.charset.isEmpty())
					mbp.setText(this.msg, this.charset);
				else if(this.subType != null && !this.subType.isEmpty())
					message.setText(this.msg, null, this.subType);
				else
					mbp.setText(this.msg);
				//if type is text/html and not just one word like html, must use setContent or error will occur
				if(this.subType != null && !this.subType.isEmpty() && this.subType.contains("/"))
					mbp.setContent(this.msg, this.subType);
		        multipart.addBodyPart(mbp);
		        // Add Attachments 
				if(!this.attaches.isEmpty()) 
					this.wrapFilesToMultipart(message, multipart);
				if(!this.attachesBytes.isEmpty())  
					this.wrapBytesToMultipart(message, multipart); 
			}else {
				// Otherwise set the actual message 
				if(this.charset != null && !this.charset.isEmpty() && this.subType != null && !this.subType.isEmpty())
					message.setText(this.msg, this.charset, this.subType);
				else if(this.charset != null && !this.charset.isEmpty())
					message.setText(this.msg, this.charset);
				else if(this.subType != null && !this.subType.isEmpty())
					message.setText(this.msg, null, this.subType);
				else
					message.setText(this.msg);
				//if type is text/html and not just one word like html, must use setContent or error will occur
				if(this.subType != null && !this.subType.isEmpty() && this.subType.contains("/"))
					message.setContent(this.msg, this.subType);
			}
			// Send message
			Transport.send(message);
			return true;
		}catch (MessagingException ex)  {
			LOG.error("Error ... sending email ... ");
			ex.printStackTrace();
		}
		return false;
	}
	
	public static boolean validateEmail(String email) {
		return email != null && !email.isEmpty() && email.matches(EMAIL_REGEXP);
	}
	
	public static boolean validateEmails(String emails) {
		String aux[] = emails.split(",");
		for(String email : aux)
			if(!validateEmail(email))
				return false;
		return true;
	}

	public EmailMessage multipleRecipients(boolean flag) {
		this.multipleRecipients = flag;
		return this;
	}
	
	public EmailMessage replyTo(String emails) {
		this.replyTo = emails;
		return this;
	} 
	
	protected void wrapFilesToMultipart(MimeMessage message,  Multipart multipart) throws MessagingException, IOException { 
		for(File attach : this.attaches) {
			// Create the message part 
			MimeBodyPart messageBodyPart = new MimeBodyPart();
	         messageBodyPart.attachFile(attach);
	         // Set message part 
	         multipart.addBodyPart(messageBodyPart);
		} 
		// Send the complete message parts 
        message.setContent(multipart);
	} 
	
	protected void wrapBytesToMultipart(MimeMessage message, Multipart multipart) throws MessagingException { 
		for(Attachment obj : this.attachesBytes){
			MimeBodyPart messageBodyPart = new MimeBodyPart(); 
			ByteArrayDataSource bds = new ByteArrayDataSource(obj.content, obj.getType());
			bds.setName(obj.getName()); 
			messageBodyPart.setDataHandler(new DataHandler(bds)); 
			messageBodyPart.setFileName(bds.getName()); 
			// Set message part 
	        multipart.addBodyPart(messageBodyPart);
		}
		// Send the complete message parts 
        message.setContent(multipart); 
	}

	/**
	 * @param cc the cc to set
	 */
	public EmailMessage setCc(String cc) {
		this.cc = cc.replace(";", ",");
		return this;
	}

	/**
	 * @param bcc the bcc to set
	 */
	public EmailMessage setBcc(String bcc) {
		this.bcc = bcc.replace(";", ",");
		return this;
	}

	public static class Attachment{ 
				
		private byte[] content; 
		private String name; 
		private String type;
		
		public Attachment(byte[] content,String name, String type) {			
			this.content = content;
			this.name = name;
			this.type = type;
		}
		
		public Attachment() {
		
		}

		public byte[] getContent() {
			return content;
		}
		public void setContent(byte[] content) {
			this.content = content;
		}
		public String getName() {
			return name;
		}
		public void setName(String name) {
			this.name = name;
		}
		public String getType() {
			return type;
		}
		public void setType(String type) {
			this.type = type;
		} 
		
	}
	
	public static class PdexTemplate{
		
		public PdexTemplate() {}
		
		
		public static String getCorpoFormatado(String boxTitle, String msgBoasVindas, String[] paragrafos, String []textoBtnAcao, String []hrefBtnAcao, String helpLink) {
			if(paragrafos.length == 0 || msgBoasVindas.isEmpty()) return "";
			 String body = ""
	                + "
" + "" + "
" + "" + " " + " " + "
" + "
" + "" + "" + "" + "" + " " + " " + "
" + "" + "" + " " + " " + " " + " " + " "; if (textoBtnAcao != null && textoBtnAcao.length > 0 && hrefBtnAcao != null && hrefBtnAcao.length > 0 && hrefBtnAcao.length == textoBtnAcao.length) { for(int i = 0 ; i < hrefBtnAcao.length; i++) { // Botao Accao body += "" + ""; } } else { // Funciona tipo uma margem antes do rodape body += ""; } body += ""; body += "" + " " + " " + "
" + " " + boxTitle + "" + "
" + "

" + msgBoasVindas + "

"; // Paragrafos for (String paragrafo : paragrafos) { body += "

" + "" + "" + paragrafo + "

"; } body += "
" + "" + "" + "
" + "" + ""+ textoBtnAcao[i] + "" + "

"; // Rodape body += "

" + " Click +info" + "

" + "
" + "
"; return body; } } }