Java Mail Api

By ukmodak | March 31st 2024 10:34:01 AM | viewed 510 times
package com.allClass.ukjavamailapi;

import java.io.UnsupportedEncodingException;
import java.util.Date;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
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;

public class EmailUtil {

	/**
	 * Utility method to send simple HTML email
	 * @param session
	 * @param toEmail
	 * @param subject
	 * @param body
	 */
	public static void sendEmail(Session session, String toEmail, String subject, String body){
		try
	    {
	             MimeMessage msg = new MimeMessage(session);
	                 //set message headers
				  msg.addHeader("Content-type", "text/HTML; charset=UTF-8");
				  msg.addHeader("format", "flowed");
				  msg.addHeader("Content-Transfer-Encoding", "8bit");
				  msg.setFrom(new InternetAddress("uzzal@gmail.com", "from mail"));
				  msg.setReplyTo(InternetAddress.parse(toEmail, false));
				  msg.setSubject(subject, "UTF-8");
				  msg.setText(body, "UTF-8");
				  msg.setSentDate(new Date());
				  msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail, false));
				  System.out.println("Message is ready");
				  Transport.send(msg);
				  System.out.println("EMail Sent Successfully!!");
	    }
	    catch (Exception e) {
	      e.printStackTrace();
	    }
	}
	
			/**
		 * Utility method to send email with attachment
		 * @param session
		 * @param toEmail
		 * @param subject
		 * @param body
		 */
     public static void sendAttachmentEmail(Session session, String toEmail, String subject, String body,String file_name_with_path){
			try{
				 MimeMessage msg = new MimeMessage(session);
				 msg.addHeader("Content-type", "text/HTML; charset=UTF-8");
				 msg.addHeader("format", "flowed");
				 msg.addHeader("Content-Transfer-Encoding", "8bit");
				 msg.setFrom(new InternetAddress("uzzal@gmail.com", "NoReply-JD"));
				 msg.setReplyTo(InternetAddress.parse(toEmail, false));
				 msg.setSubject(subject, "UTF-8");
				 msg.setSentDate(new Date());
				 msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail, false));
				     // Create the message body part
				 BodyPart messageBodyPart = new MimeBodyPart();
				     // Fill the message
				 messageBodyPart.setText(body);
				      // Create a multipart message for attachment
				 Multipart multipart = new MimeMultipart();
				      // Set text message part
				 multipart.addBodyPart(messageBodyPart);
				     // Second part is attachment
				 messageBodyPart = new MimeBodyPart();
				      //String filename = "abc.txt";
				 String filename = file_name_with_path;
				 DataSource source = new FileDataSource(filename);
				 messageBodyPart.setDataHandler(new DataHandler(source));
				 messageBodyPart.setFileName(filename);
				 multipart.addBodyPart(messageBodyPart);
				     // Send the complete message parts
				 msg.setContent(multipart);

							 // Send message
				 Transport.send(msg);
				 System.out.println("EMail Sent Successfully with attachment!!");

			  }catch (MessagingException e) {
				 e.printStackTrace();
			  } catch (UnsupportedEncodingException e) {
				 e.printStackTrace();
			}
       }
	   
	   /**
		 * Utility method to send image in email body
		 * @param session
		 * @param toEmail
		 * @param subject
		 * @param body
		 */
		public static void sendImageEmail(Session session, String toEmail, String subject, String body,String imgPathWithName){
			try{
				 MimeMessage msg = new MimeMessage(session);
				 msg.addHeader("Content-type", "text/HTML; charset=UTF-8");
				 msg.addHeader("format", "flowed");
				 msg.addHeader("Content-Transfer-Encoding", "8bit");
				 msg.setFrom(new InternetAddress("uzzalkm@gmail.com", "NoReply-JD"));
				 msg.setReplyTo(InternetAddress.parse(toEmail, false));
				 msg.setSubject(subject, "UTF-8");
				 msg.setSentDate(new Date());
				 msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail, false));
				     // Create the message body part
				 BodyPart messageBodyPart = new MimeBodyPart();
				 messageBodyPart.setText(body);
				     // Create a multipart message for attachment
				 Multipart multipart = new MimeMultipart();
				     // Set text message part
				 multipart.addBodyPart(messageBodyPart);
				     // Second part is image attachment
				 messageBodyPart = new MimeBodyPart();
				      //String filename = "image.png";
				 String filename = imgPathWithName;
				 
				 DataSource source = new FileDataSource(filename);
				 messageBodyPart.setDataHandler(new DataHandler(source));
				 messageBodyPart.setFileName(filename);
				     //Trick is to add the content-id header here
				 messageBodyPart.setHeader("Content-ID", "image_id");
				 multipart.addBodyPart(messageBodyPart);
				     //third part for displaying image in the email body
				 messageBodyPart = new MimeBodyPart();
				 messageBodyPart.setContent("<h1>Attached Image</h1>" +
							 "<img src='cid:image_id'>", "text/html");
				 multipart.addBodyPart(messageBodyPart);
				 
				 //Set the multipart message to the email message
				 msg.setContent(multipart);

							 // Send message
				 Transport.send(msg);
				 System.out.println("EMail Sent Successfully with image!!");

			  }catch (MessagingException e) {
				 e.printStackTrace();
			  } catch (UnsupportedEncodingException e) {
				 e.printStackTrace();
			}
		}
	   
}

Using SSL

package com.allClass.ukjavamailapi;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import java.util.Properties;

public class SSLEmailByUk {

	/**
	   Outgoing Mail (SMTP) Server
	   requires TLS or SSL: smtp.gmail.com (use authentication)
	   Use Authentication: Yes
	   Port for SSL: 465
	 */

	public Properties props;
	public Authenticator auth;


	public SSLEmailByUk(){

		final String fromEmail = "info@ukmodak.com"; //requires valid gmail id
		final String password = "**********"; // correct password for gmail id


		System.out.println("SSLEmail Start");  // okkk
		        this.props = new Properties();
				this.props.put("mail.smtp.host", "mail.ukmodak.com"); //SMTP Host
				this.props.put("mail.smtp.socketFactory.port", "465"); //SSL Port
				this.props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); //SSL Factory Class
				this.props.put("mail.smtp.auth", "true"); //Enabling SMTP Authentication
				this.props.put("mail.smtp.port", "465"); //SMTP Port
		        this.props.put("mail.smtp.localhost", "www.ukmodak.com");

		//create Authenticator object to pass in Session.getInstance argument

		this.auth = new Authenticator() {
			//override the getPasswordAuthentication method
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(fromEmail, password);
			}
		};

	}


	public void ukSendMail(String toEmail,String subject, String body){

		Session session = Session.getInstance(this.props, this.auth);
		EmailUtil.sendEmail(session, toEmail,subject, body);

	}

	public void ukSendAtachmentMail(String toEmail,String subject, String body){

		Session session = Session.getInstance(this.props, this.auth);
		EmailUtil.sendAttachmentEmail(session, toEmail,subject,body);

	}

	public void ukSendImageEmail(String toEmail,String subject, String body){

		Session session = Session.getInstance(this.props, this.auth);
		EmailUtil.sendAttachmentEmail(session, toEmail,subject,body);

	}
}

Using TLS

package com.allClass.ukjavamailapi;

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;

public class TLSEmailByUk {

	/**
	   Outgoing Mail (SMTP) Server
	   requires TLS or SSL: smtp.gmail.com (use authentication)
	   Use Authentication: Yes
	   Port for TLS/STARTTLS: 587
	 */
	 
	 public Properties props;
	 public Authenticator auth;
	 
	 
	 public TLSEmailByUk(){

		
		 final String fromEmail = "uzzal@gmail.com"; //requires valid gmail id
		 final String password = "********"; // authenticate password for gmail
		
		System.out.println("TLSEmail Start");
				this.props = new Properties();
				this.props.put("mail.smtp.host", "smtp.office365.com"); //SMTP Host
				this.props.put("mail.smtp.port", "587"); //TLS Port
				this.props.put("mail.smtp.auth", "true"); //enable authentication
				this.props.put("mail.smtp.starttls.enable", "true"); //enable STARTTLS
		        this.props.put("mail.smtp.port", "587"); //SMTP Port
		        this.props.put("mail.smtp.socketFactory.fallback", "false");
		        this.props.put("mail.debug", "true");

		
                //create Authenticator object to pass in Session.getInstance argument

				this.auth = new Authenticator() {
					//override the getPasswordAuthentication method
					protected PasswordAuthentication getPasswordAuthentication() {
						return new PasswordAuthentication(fromEmail, password);
					}
				};
		 
	 }
	 
	 
	 public void ukSendMail(String toEmail,String subject, String body){
		 
		 Session session = Session.getInstance(this.props, this.auth);
		 EmailUtil.sendEmail(session, toEmail,subject, body);
		 
	 }
	 
	 public void ukSendAtachmentMail(String toEmail,String subject, String body){
		 
		 Session session = Session.getInstance(this.props, this.auth);
		 EmailUtil.sendAttachmentEmail(session, toEmail,subject,body);
		 
	 }
	 
	 public void ukSendImageEmail(String toEmail,String subject, String body){
		 
		 Session session = Session.getInstance(this.props, this.auth);
		 EmailUtil.sendAttachmentEmail(session, toEmail,subject,body);
		 
	 }	
}
bONEandALL
Visitor

Total : 26654

Today :3

Today Visit Country :

  • France
  • United States