Smtp Email Authentication Required. Check Your Username/password and Try Again. Hp Scan to Email

Today nosotros will await into JavaMail Example to ship email in coffee programs. Sending emails is 1 of the common tasks in real life applications and that's why Java provides robust JavaMail API that we can use to send emails using SMTP server. JavaMail API supports both TLS and SSL authentication for sending emails.

JavaMail Example

javamail example, send mail in java, java smtp, java send email

Today we volition learn how to utilise JavaMail API to send emails using SMTP server with no authentication, TLS and SSL hallmark and how to transport attachments and attach and use images in the email torso. For TLS and SSL authentication, I am using GMail SMTP server because it supports both of them. You can also choose to go for a Java mail server depending on your project needs.

JavaMail API is not part of standard JDK, so y'all will take to download it from information technology's official website i.e JavaMail Abode Folio. Download the latest version of the JavaMail reference implementation and include it in your projection build path. The jar file name will be javax.mail.jar.

If you are using Maven based project, just add beneath dependency in your project.

            <dependency> 	<groupId>com.sun.mail</groupId> 	<artifactId>javax.postal service</artifactId> 	<version>one.5.5</version> </dependency>                      

Java Program to send email contains following steps:

  1. Creating javax.mail.Session object
  2. Creating javax.mail.internet.MimeMessage object, we have to set dissimilar properties in this object such as recipient email address, Electronic mail Bailiwick, Reply-To email, email torso, attachments etc.
  3. Using javax.postal service.Transport to transport the email bulletin.

The logic to create session differs based on the type of SMTP server, for instance if SMTP server doesn't require any authentication we can create the Session object with some simple properties whereas if it requires TLS or SSL authentication, then logic to create will differ.

So I will create a utility class with some utility methods to send emails and then I volition employ this utility method with dissimilar SMTP servers.

JavaMail Example Programme

Our EmailUtil class that has a single method to ship electronic mail looks like below, it requires javax.mail.Session and another required fields equally arguments. To keep information technology uncomplicated, some of the arguments are hard coded but y'all can extend this method to pass them or read it from some config files.

            package com.journaldev.postal service;  import java.io.UnsupportedEncodingException; import java.util.Date;  import javax.activation.DataHandler; import javax.activation.DataSource; import javax.activation.FileDataSource; import javax.postal service.BodyPart; import javax.mail.Bulletin; import javax.mail.MessagingException; import javax.mail.Multipart; import javax.mail service.Session; import javax.mail.Transport; import javax.mail service.net.InternetAddress; import javax.mail.net.MimeBodyPart; import javax.mail.net.MimeMessage; import javax.post.internet.MimeMultipart;  public form EmailUtil {  	/** 	 * Utility method to send simple HTML email 	 * @param session 	 * @param toEmail 	 * @param discipline 	 * @param body 	 */ 	public static void sendEmail(Session session, Cord 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("no_reply@case.com", "NoReply-JD"));  	      msg.setReplyTo(InternetAddress.parse("no_reply@example.com", fake));  	      msg.setSubject(discipline, "UTF-8");  	      msg.setText(body, "UTF-8");  	      msg.setSentDate(new Engagement());  	      msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail, false)); 	      System.out.println("Message is ready");     	  Transport.send(msg);    	      Arrangement.out.println("Email Sent Successfully!!"); 	    } 	    grab (Exception east) { 	      east.printStackTrace(); 	    } 	} }                      

Notice that I am setting some header properties in the MimeMessage, they are used past the email clients to properly render and display the email message. Remainder of the program is simple and cocky understood.

Now let's create our program to ship e-mail without authentication.

Transport Postal service in Java using SMTP without authentication

            package com.journaldev.mail;  import java.util.Backdrop;  import javax.mail.Session;  public class SimpleEmail { 	 	public static void master(Cord[] args) { 		 	    Organization.out.println("SimpleEmail Start"); 		 	    String smtpHostServer = "smtp.example.com"; 	    String emailID = "email_me@example.com"; 	     	    Backdrop props = System.getProperties();  	    props.put("mail.smtp.host", smtpHostServer);  	    Session session = Session.getInstance(props, nix); 	     	    EmailUtil.sendEmail(session, emailID,"SimpleEmail Testing Subject", "SimpleEmail Testing Body"); 	}  }                      

Notice that I am using Session.getInstance() to become the Session object past passing the Backdrop object. We need to set the postal service.smtp.host holding with the SMTP server host. If the SMTP server is not running on default port (25), so you will also need to set mail.smtp.port property. Merely run this program with your no-authentication SMTP server and by setting recipient email id as your own electronic mail id and yous volition get the electronic mail in no time.

The program is unproblematic to understand and works well, merely in real life nigh of the SMTP servers apply some sort of authentication such as TLS or SSL authentication. And then nosotros will at present come across how to create Session object for these authentication protocols.

Send Email in Coffee SMTP with TLS Authentication

            bundle com.journaldev.mail;  import java.util.Properties;  import javax.post.Authenticator; import javax.mail.PasswordAuthentication; import javax.mail.Session;  public class TLSEmail {  	/** 	   Approachable Mail (SMTP) Server 	   requires TLS or SSL: smtp.gmail.com (utilise authentication) 	   Utilize Hallmark: Yep 	   Port for TLS/STARTTLS: 587 	 */ 	public static void primary(String[] args) { 		terminal String fromEmail = "myemailid@gmail.com"; //requires valid gmail id 		final Cord password = "mypassword"; // correct password for gmail id 		final String toEmail = "myemail@yahoo.com"; // tin be whatever email id  		 		System.out.println("TLSEmail Start"); 		Backdrop props = new Backdrop(); 		props.put("mail.smtp.host", "smtp.gmail.com"); //SMTP Host 		props.put("mail.smtp.port", "587"); //TLS Port 		props.put("mail.smtp.auth", "truthful"); //enable authentication 		props.put("mail.smtp.starttls.enable", "true"); //enable STARTTLS 		                 //create Authenticator object to laissez passer in Session.getInstance argument 		Authenticator auth = new Authenticator() { 			//override the getPasswordAuthentication method 			protected PasswordAuthentication getPasswordAuthentication() { 				render new PasswordAuthentication(fromEmail, password); 			} 		}; 		Session session = Session.getInstance(props, auth); 		 		EmailUtil.sendEmail(session, toEmail,"TLSEmail Testing Subject field", "TLSEmail Testing Trunk"); 		 	}  	 }                      

Since I am using GMail SMTP server that is accessible to all, y'all tin can prepare the correct variables in above program and run for yourself. Believe me information technology works!! 🙂

Coffee SMTP Case with SSL Hallmark

            packet com.journaldev.mail;  import java.util.Properties;  import javax.mail.Authenticator; import javax.postal service.PasswordAuthentication; import javax.post.Session;  public class SSLEmail {  	/** 	   Outgoing Mail service (SMTP) Server 	   requires TLS or SSL: smtp.gmail.com (employ authentication) 	   Utilize Authentication: Yes 	   Port for SSL: 465 	 */ 	public static void main(Cord[] args) { 		last String fromEmail = "myemailid@gmail.com"; //requires valid gmail id 		final String countersign = "mypassword"; // correct countersign for gmail id 		terminal Cord toEmail = "myemail@yahoo.com"; // can exist any email id  		 		Arrangement.out.println("SSLEmail Start"); 		Properties props = new Properties(); 		props.put("mail service.smtp.host", "smtp.gmail.com"); //SMTP Host 		props.put("post.smtp.socketFactory.port", "465"); //SSL Port 		props.put("mail.smtp.socketFactory.class", 				"javax.net.ssl.SSLSocketFactory"); //SSL Mill Class 		props.put("mail.smtp.auth", "truthful"); //Enabling SMTP Authentication 		props.put("mail.smtp.port", "465"); //SMTP Port 		 		Authenticator auth = new Authenticator() { 			//override the getPasswordAuthentication method 			protected PasswordAuthentication getPasswordAuthentication() { 				return new PasswordAuthentication(fromEmail, password); 			} 		}; 		 		Session session = Session.getDefaultInstance(props, auth); 		Organization.out.println("Session created"); 	        EmailUtil.sendEmail(session, toEmail,"SSLEmail Testing Subject", "SSLEmail Testing Body");  	        EmailUtil.sendAttachmentEmail(session, toEmail,"SSLEmail Testing Field of study with Zipper", "SSLEmail Testing Body with Attachment");  	        EmailUtil.sendImageEmail(session, toEmail,"SSLEmail Testing Bailiwick with Image", "SSLEmail Testing Torso with Image");  	}  }                      

The programme is near aforementioned as TLS hallmark, just some properties are different. Every bit you lot can see that I am calling some other methods from EmailUtil class to send attachment and image in email simply I haven't defined them withal. Actually I kept them to evidence later on and keep it simple at start of the tutorial.

JavaMail Example – transport mail in java with zipper

To send a file every bit attachment, we demand to create an object of javax.post.internet.MimeBodyPart and javax.mail service.internet.MimeMultipart. First add together the body role for the text message in the email so use FileDataSource to attach the file in second role of the multipart body. The method looks like below.

            /**  * Utility method to send e-mail with attachment  * @param session  * @param toEmail  * @param subject  * @param body  */ public static void sendAttachmentEmail(Session session, String toEmail, String subject field, String body){ 	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("no_reply@example.com", "NoReply-JD"));  	     msg.setReplyTo(InternetAddress.parse("no_reply@example.com", false));  	     msg.setSubject(discipline, "UTF-8");  	     msg.setSentDate(new Date());  	     msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail, false)); 	                // Create the message body function          BodyPart messageBodyPart = new MimeBodyPart();           // Fill the message          messageBodyPart.setText(body);                    // Create a multipart message for attachment          Multipart multipart = new MimeMultipart();           // Ready text message part          multipart.addBodyPart(messageBodyPart);           // 2d part is zipper          messageBodyPart = new MimeBodyPart();          String filename = "abc.txt";          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          Ship.send(msg);          System.out.println("E-mail Sent Successfully with zipper!!");       }catch (MessagingException e) {          e.printStackTrace();       } catch (UnsupportedEncodingException east) { 		 east.printStackTrace(); 	} }                      

The program might look complex at first expect only information technology'due south simple, only create a body role for text message and some other body part for attachment and then add them to the multipart. Y'all tin can extend this method to attach multiple files too.

JavaMail example – ship mail in java with paradigm

Since nosotros can create HTML body bulletin, if the epitome file is located at some server location we can employ img chemical element to show them in the message. Simply sometimes nosotros want to attach the image in the email and and so use it in the email torso itself. You must have seen so many emails that have paradigm attachments and are also used in the email bulletin.

The trick is to attach the prototype file like whatever other zipper and so set up the Content-ID header for image file and so utilize the same content id in the electronic mail message body with <img src='cid:image_id'>.

            /**  * Utility method to send paradigm in e-mail trunk  * @param session  * @param toEmail  * @param subject  * @param body  */ public static void sendImageEmail(Session session, String toEmail, String discipline, String body){ 	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("no_reply@example.com", "NoReply-JD"));  	     msg.setReplyTo(InternetAddress.parse("no_reply@example.com", false));  	     msg.setSubject(subject, "UTF-8");  	     msg.setSentDate(new Date());  	     msg.setRecipients(Bulletin.RecipientType.TO, InternetAddress.parse(toEmail, false)); 	                // Create the message trunk role          BodyPart messageBodyPart = new MimeBodyPart();           messageBodyPart.setText(trunk);                    // Create a multipart message for attachment          Multipart multipart = new MimeMultipart();           // Set text bulletin part          multipart.addBodyPart(messageBodyPart);           // Second office is paradigm attachment          messageBodyPart = new MimeBodyPart();          String filename = "prototype.png";          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 trunk          messageBodyPart = new MimeBodyPart();          messageBodyPart.setContent("<h1>Fastened Image</h1>" +         		     "<img src='cid:image_id'>", "text/html");          multipart.addBodyPart(messageBodyPart);                    //Set up the multipart message to the electronic mail message          msg.setContent(multipart);           // Ship bulletin          Transport.send(msg);          Organization.out.println("EMail Sent Successfully with image!!");       }catch (MessagingException east) {          eastward.printStackTrace();       } grab (UnsupportedEncodingException due east) { 		 e.printStackTrace(); 	} }                      

JavaMail API Troubleshooting Tips

  1. java.net.UnknownHostException comes when your organization is not able to resolve the IP address for the SMTP server, it might be wrong or non accessible from your network. For instance, GMail SMTP server is smtp.gmail.com and if I use smtp.google.com, I will get this exception. If the hostname is correct, attempt to ping the server through command line to make sure it'southward accessible from your organization.
                    pankaj@Pankaj:~/Lawmaking$ ping smtp.gmail.com PING gmail-smtp-msa.l.google.com (74.125.129.108): 56 information bytes 64 bytes from 74.125.129.108: icmp_seq=0 ttl=46 time=38.308 ms 64 bytes from 74.125.129.108: icmp_seq=ane ttl=46 time=42.247 ms 64 bytes from 74.125.129.108: icmp_seq=two ttl=46 time=38.164 ms 64 bytes from 74.125.129.108: icmp_seq=3 ttl=46 time=53.153 ms                              
  2. If your program is stuck in Ship ship() method call, bank check that SMTP port is correct. If it's correct then apply telnet to verify that it's attainable from yous machine, you volition get output like beneath.
                    pankaj@Pankaj:~/CODE$ telnet smtp.gmail.com 587 Trying 2607:f8b0:400e:c02::6d... Connected to gmail-smtp-msa.50.google.com. Escape character is '^]'. 220 mx.google.com ESMTP sx8sm78485186pab.5 - gsmtp HELO 250 mx.google.com at your service                              

That's all for JavaMail case to ship mail in coffee using SMTP server with different authentication protocols, attachment and images. I hope it will solve all your needs for sending emails in java programs.

greenningdom.blogspot.com

Source: https://www.journaldev.com/2532/javamail-example-send-mail-in-java-smtp

0 Response to "Smtp Email Authentication Required. Check Your Username/password and Try Again. Hp Scan to Email"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel