Android Please Log in via Your Web Browser and 534 5 7 14 Then Try Again Javamail
Today we will look into JavaMail Example to send email in coffee programs. Sending emails is one of the mutual tasks in existent life applications and that'south why Java provides robust JavaMail API that we can use to ship emails using SMTP server. JavaMail API supports both TLS and SSL authentication for sending emails.
JavaMail Example
Today we will learn how to use JavaMail API to transport emails using SMTP server with no authentication, TLS and SSL authentication and how to send attachments and attach and apply images in the email body. For TLS and SSL authentication, I am using GMail SMTP server because it supports both of them. You can also choose to get for a Java mail server depending on your project needs.
JavaMail API is not role of standard JDK, so you will have to download it from it'south official website i.e JavaMail Home Page. Download the latest version of the JavaMail reference implementation and include it in your project build path. The jar file name will exist javax.mail.jar.
If you are using Maven based project, only add below dependency in your project.
<dependency> <groupId>com.sun.mail</groupId> <artifactId>javax.mail service</artifactId> <version>i.v.five</version> </dependency> Java Plan to send e-mail contains following steps:
- Creating
javax.postal service.Sessionobject - Creating
javax.postal service.internet.MimeMessageobject, we take to set unlike properties in this object such as recipient e-mail accost, Email Subject, Reply-To e-mail, email body, attachments etc. - Using
javax.mail.Sendto ship the electronic mail message.
The logic to create session differs based on the type of SMTP server, for example if SMTP server doesn't require whatever hallmark we can create the Session object with some uncomplicated backdrop whereas if it requires TLS or SSL authentication, and then logic to create will differ.
So I will create a utility form with some utility methods to send emails and and so I will use this utility method with dissimilar SMTP servers.
JavaMail Case Program
Our EmailUtil class that has a single method to ship e-mail looks like below, it requires javax.mail.Session and some other required fields every bit arguments. To keep it elementary, some of the arguments are difficult coded but you tin extend this method to pass them or read it from some config files.
parcel com.journaldev.mail; import java.io.UnsupportedEncodingException; import java.util.Appointment; import javax.activation.DataHandler; import javax.activation.DataSource; import javax.activation.FileDataSource; import javax.post.BodyPart; import javax.mail.Bulletin; import javax.postal service.MessagingException; import javax.mail.Multipart; import javax.mail.Session; import javax.mail.Transport; import javax.mail.net.InternetAddress; import javax.mail service.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.postal service.net.MimeMultipart; public course EmailUtil { /** * Utility method to send simple HTML email * @param session * @param toEmail * @param subject * @param torso */ public static void sendEmail(Session session, String toEmail, String subject, String body){ try { MimeMessage msg = new MimeMessage(session); //gear up message headers msg.addHeader("Content-blazon", "text/HTML; charset=UTF-viii"); 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", simulated)); msg.setSubject(subject, "UTF-8"); msg.setText(torso, "UTF-8"); msg.setSentDate(new Date()); msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail, imitation)); System.out.println("Message is ready"); Transport.ship(msg); System.out.println("EMail Sent Successfully!!"); } grab (Exception e) { e.printStackTrace(); } } } Detect that I am setting some header properties in the MimeMessage, they are used by the email clients to properly render and display the email bulletin. Rest of the program is simple and self understood.
At present let's create our plan to ship email without hallmark.
Send Mail in Coffee using SMTP without authentication
package com.journaldev.mail; import java.util.Properties; import javax.mail.Session; public grade SimpleEmail { public static void main(String[] args) { Organization.out.println("SimpleEmail Commencement"); String smtpHostServer = "smtp.example.com"; String emailID = "email_me@example.com"; Properties props = System.getProperties(); props.put("postal service.smtp.host", smtpHostServer); Session session = Session.getInstance(props, null); EmailUtil.sendEmail(session, emailID,"SimpleEmail Testing Bailiwick", "SimpleEmail Testing Body"); } } Detect that I am using Session.getInstance() to get the Session object by passing the Backdrop object. Nosotros need to set the postal service.smtp.host property with the SMTP server host. If the SMTP server is non running on default port (25), and so yous will also need to set mail service.smtp.port property. Just run this program with your no-authentication SMTP server and by setting recipient e-mail id as your ain email id and you will get the email in no fourth dimension.
The program is elementary to sympathize and works well, but in real life most of the SMTP servers use some sort of hallmark such every bit TLS or SSL authentication. And so we will at present come across how to create Session object for these authentication protocols.
Send E-mail in Java SMTP with TLS Authentication
packet com.journaldev.mail; import java.util.Backdrop; import javax.mail.Authenticator; import javax.postal service.PasswordAuthentication; import javax.mail.Session; public class TLSEmail { /** Outgoing Mail (SMTP) Server requires TLS or SSL: smtp.gmail.com (use authentication) Employ Hallmark: Yes Port for TLS/STARTTLS: 587 */ public static void main(String[] args) { final String fromEmail = "myemailid@gmail.com"; //requires valid gmail id final String countersign = "mypassword"; // right password for gmail id last String toEmail = "myemail@yahoo.com"; // can be any email id Organisation.out.println("TLSEmail First"); Backdrop props = new Properties(); props.put("mail service.smtp.host", "smtp.gmail.com"); //SMTP Host props.put("mail.smtp.port", "587"); //TLS Port props.put("mail.smtp.auth", "true"); //enable authentication props.put("mail.smtp.starttls.enable", "true"); //enable STARTTLS //create Authenticator object to pass in Session.getInstance statement Authenticator auth = new Authenticator() { //override the getPasswordAuthentication method protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(fromEmail, password); } }; Session session = Session.getInstance(props, auth); EmailUtil.sendEmail(session, toEmail,"TLSEmail Testing Subject", "TLSEmail Testing Body"); } } Since I am using GMail SMTP server that is attainable to all, you can set the right variables in above program and run for yourself. Believe me it works!! 🙂
Java SMTP Instance with SSL Authentication
parcel com.journaldev.mail; import java.util.Properties; import javax.post.Authenticator; import javax.mail.PasswordAuthentication; import javax.mail.Session; public grade SSLEmail { /** Outgoing Postal service (SMTP) Server requires TLS or SSL: smtp.gmail.com (employ hallmark) Employ Hallmark: Yes Port for SSL: 465 */ public static void main(Cord[] args) { final String fromEmail = "myemailid@gmail.com"; //requires valid gmail id final String password = "mypassword"; // correct countersign for gmail id terminal String toEmail = "myemail@yahoo.com"; // can be any electronic mail id System.out.println("SSLEmail Start"); Backdrop props = new Properties(); props.put("mail.smtp.host", "smtp.gmail.com"); //SMTP Host props.put("mail.smtp.socketFactory.port", "465"); //SSL Port props.put("post.smtp.socketFactory.grade", "javax.net.ssl.SSLSocketFactory"); //SSL Manufactory Class props.put("mail.smtp.auth", "true"); //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 area", "SSLEmail Testing Trunk"); EmailUtil.sendAttachmentEmail(session, toEmail,"SSLEmail Testing Subject with Attachment", "SSLEmail Testing Body with Attachment"); EmailUtil.sendImageEmail(session, toEmail,"SSLEmail Testing Subject with Epitome", "SSLEmail Testing Trunk with Image"); } } The programme is most same every bit TLS hallmark, only some properties are different. As yous can run into that I am calling another methods from EmailUtil class to transport attachment and paradigm in email but I oasis't defined them even so. Actually I kept them to evidence later and keep it simple at get-go of the tutorial.
JavaMail Example – send mail in java with zipper
To send a file as attachment, we need to create an object of javax.postal service.internet.MimeBodyPart and javax.mail.internet.MimeMultipart. Beginning add the torso part for the text message in the email and then utilise FileDataSource to attach the file in 2d office of the multipart body. The method looks like below.
/** * Utility method to send email with attachment * @param session * @param toEmail * @param discipline * @param body */ public static void sendAttachmentEmail(Session session, String toEmail, String field of study, String torso){ effort{ 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@case.com", "NoReply-JD")); msg.setReplyTo(InternetAddress.parse("no_reply@example.com", false)); msg.setSubject(subject, "UTF-viii"); msg.setSentDate(new Date()); msg.setRecipients(Bulletin.RecipientType.TO, InternetAddress.parse(toEmail, fake)); // Create the message body part BodyPart messageBodyPart = new MimeBodyPart(); // Make full the message messageBodyPart.setText(body); // Create a multipart bulletin for zipper Multipart multipart = new MimeMultipart(); // Set text message part multipart.addBodyPart(messageBodyPart); // Second office is attachment 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 Send.ship(msg); System.out.println("EMail Sent Successfully with attachment!!"); }take hold of (MessagingException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } The plan might wait complex at kickoff wait but information technology's unproblematic, just create a body part for text message and some other body role for attachment and then add together them to the multipart. You can extend this method to attach multiple files likewise.
JavaMail case – send mail in coffee with prototype
Since we can create HTML body bulletin, if the image file is located at some server location nosotros can use img element to evidence them in the message. But sometimes we want to attach the image in the e-mail and then use it in the email body itself. You lot must have seen so many emails that accept image attachments and are too used in the email message.
The trick is to attach the image file like whatsoever other attachment and and then prepare the Content-ID header for epitome file and then use the same content id in the email message body with <img src='cid:image_id'>.
/** * Utility method to send epitome in email body * @param session * @param toEmail * @param subject area * @param body */ public static void sendImageEmail(Session session, Cord toEmail, String subject, 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", imitation)); msg.setSubject(bailiwick, "UTF-viii"); 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 zipper messageBodyPart = new MimeBodyPart(); String filename = "epitome.png"; DataSource source = new FileDataSource(filename); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(filename); //Pull a fast one on is to add the content-id header here messageBodyPart.setHeader("Content-ID", "image_id"); multipart.addBodyPart(messageBodyPart); //third part for displaying image in the electronic mail body messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent("<h1>Fastened Image</h1>" + "<img src='cid:image_id'>", "text/html"); multipart.addBodyPart(messageBodyPart); //Gear up the multipart message to the electronic mail message msg.setContent(multipart); // Send bulletin Transport.transport(msg); System.out.println("Electronic mail Sent Successfully with prototype!!"); }grab (MessagingException east) { eastward.printStackTrace(); } catch (UnsupportedEncodingException e) { eastward.printStackTrace(); } } JavaMail API Troubleshooting Tips
-
java.cyberspace.UnknownHostExceptioncomes when your system is not able to resolve the IP accost for the SMTP server, it might be wrong or non accessible from your network. For example, GMail SMTP server is smtp.gmail.com and if I use smtp.google.com, I will get this exception. If the hostname is correct, try to ping the server through command line to make certain it's accessible from your organisation.pankaj@Pankaj:~/Code$ ping smtp.gmail.com PING gmail-smtp-msa.l.google.com (74.125.129.108): 56 data 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=one ttl=46 fourth dimension=42.247 ms 64 bytes from 74.125.129.108: icmp_seq=2 ttl=46 fourth dimension=38.164 ms 64 bytes from 74.125.129.108: icmp_seq=3 ttl=46 time=53.153 ms - If your plan is stuck in Transport send() method call, cheque that SMTP port is correct. If it's correct and then use telnet to verify that it'southward accessible from you automobile, you will get output like below.
pankaj@Pankaj:~/CODE$ telnet smtp.gmail.com 587 Trying 2607:f8b0:400e:c02::6d... Connected to gmail-smtp-msa.50.google.com. Escape grapheme is '^]'. 220 mx.google.com ESMTP sx8sm78485186pab.v - gsmtp HELO 250 mx.google.com at your service
That's all for JavaMail example to send post in java using SMTP server with dissimilar authentication protocols, attachment and images. I hope it will solve all your needs for sending emails in coffee programs.
blanchettefaverry.blogspot.com
Source: https://www.journaldev.com/2532/javamail-example-send-mail-in-java-smtp
0 Response to "Android Please Log in via Your Web Browser and 534 5 7 14 Then Try Again Javamail"
Post a Comment