Send email by gmail in java

Java + Gmail SMTP: Send Email Text, HTML and Attachment Example

This page will provide complete tutorial to send email using java and Gmail SMTP. In our example, we will send text, html and attachment in email for the demo. Java provides JavaMail API which uses mail and activation jar. To send email a session is created. Using this session instance we create MimeMessage and finally using Transport.send() method, we send email. To send html content and attachment , JavaMail APi provides MimeMultipart and MimeBodyPart classes. In this tutorial we will learn to send email with

1. Simple text
2. Text and attachment
3. Html content and attachment

To run the program in local machine, we need to make our Gmail account less secure using below steps.

1. Login to Gmail.
2. Access the URL as https://www.google.com/settings/security/lesssecureapps
3. Select «Turn on»

Session and Authenticator

javax.mail.Session is a mail session. Session can be shared and unshared. Default session can be shared by multiple desktop applications. It keeps default values for the mail property. The default properties of session can be overridden as

Properties props = new Properties(); props.put("mail.smtp.host", "smtp.gmail.com"); props.put("mail.smtp.port", "587");

Session can be created by passing properties instance and javax.mail.Authenticator. Find the code snippet.

Session session = Session.getInstance(props, new Authenticator() < protected PasswordAuthentication getPasswordAuthentication() < return new PasswordAuthentication("arvindraivns06@gmail.com", "password"); >>);

Authenticator class defines a method to return PasswordAuthentication which accepts mail id and password. If we are using Gmail SMTP, we need to pass Gmail id and our Gmail password.

MimeMessage and Transport.send()

javax.mail.internet.MimeMessage represents MIME style email message. MimeMessage implements Message abstract class and MimePart interface. Using MimeMessage class, we set TO, FROM, SUBJECT etc to send mail as below.

MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress("arvindraivns06@gmail.com")); msg.setRecipients(Message.RecipientType.TO, "arvindraivns02@gmail.com");

javax.mail.Transport.send() method finally send the email to all recipients. Transport is an abstract class used to transport message.

MimeMultipart and MimeBodyPart

In the case, if we are intended to send HTML content and attachment or both, we need to use javax.mail.internet.MimeMultipart and javax.mail.internet.MimeBodyPart classes. We create an empty MimeMultipart object which has content type as «multipart/mixed». MimeBodyPart represents MIME body part. It implements BodyPart abstract class and MimePart interface. We use these classes as

Multipart multipart = new MimeMultipart(); MimeBodyPart attachementPart = new MimeBodyPart(); attachementPart.attachFile(new File("D:/cp/pic.jpg")); multipart.addBodyPart(attachementPart);
MimeMessage.setContent(multipart);

Gradle File for Mail and Activation JAR

apply plugin: ‘java’ apply plugin: ‘eclipse’ archivesBaseName = ‘Concretepage’ version = ‘1.0-SNAPSHOT’ repositories < maven < url "https://repo.spring.io/libs-release" >mavenLocal() mavenCentral() > dependencies

Читайте также:  Collection from list java

Send Email with Simple Text

package com.concretepage; import java.util.Date; import java.util.Properties; import javax.mail.Authenticator; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; public class SendSimpleMail < public static void main(String[] args) < Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", "smtp.gmail.com"); props.put("mail.smtp.port", "587"); props.put("mail.debug", "true"); Session session = Session.getInstance(props, new Authenticator() < protected PasswordAuthentication getPasswordAuthentication() < return new PasswordAuthentication("arvindraivns06@gmail.com", "password"); >>); try < MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress("arvindraivns06@gmail.com")); msg.setRecipients(Message.RecipientType.TO, "arvindraivns02@gmail.com"); msg.setSubject("Simple Test Mail"); msg.setSentDate(new Date()); msg.setText("Hello World!"); Transport.send(msg); System.out.println("---Done---"); >catch (MessagingException mex) < mex.printStackTrace(); >> >
Subject: Simple Test Mail MIME-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit Hello World! . 250 2.0.0 OK 1424959435 c17sm1093738pdl.79 - gsmtp QUIT 221 2.0.0 closing connection c17sm1093738pdl.79 - gsmtp ---Done---

Send Email with Text and Attachment

Here we will use Multipart and create two MimeBodyPart , one for text and second for attachment.
AttachmentWithText.java

package com.concretepage; import java.io.File; import java.util.Date; import java.util.Properties; import javax.mail.Authenticator; import javax.mail.Message; 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; public class AttachmentWithText < public static void main(String[] args) < Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", "smtp.gmail.com"); props.put("mail.smtp.port", "587"); props.put("mail.debug", "true"); Session session = Session.getInstance(props, new Authenticator() < protected PasswordAuthentication getPasswordAuthentication() < return new PasswordAuthentication("arvindraivns06@gmail.com", "password"); >>); try < MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress("arvindraivns06@gmail.com")); msg.setRecipients(Message.RecipientType.TO, "arvindraivns02@gmail.com"); msg.setSubject("Text Mail with Attachment."); msg.setSentDate(new Date()); Multipart multipart = new MimeMultipart(); MimeBodyPart textPart = new MimeBodyPart(); String textContent = "Please find the Attachment."; textPart.setText(textContent); multipart.addBodyPart(textPart); MimeBodyPart attachementPart = new MimeBodyPart(); attachementPart.attachFile(new File("D:/cp/pic.jpg")); multipart.addBodyPart(attachementPart); msg.setContent(multipart); Transport.send(msg); System.out.println("---Done---"); >catch (Exception ex) < ex.printStackTrace(); >> >
------=_Part_0_1361188139.1424959525240-- . 250 2.0.0 OK 1424959535 mi9sm1225699pab.3 - gsmtp QUIT 221 2.0.0 closing connection mi9sm1225699pab.3 - gsmtp ---Done---

Send Email with Html Content and Attachment

This example is almost same as above. Here we have tried to show how to use HTML content and attachment. Create Multipart and create two MimeBodyPart , one for html content and second for attachment.
AttachementWithHtmlContent.java

package com.concretepage; import java.io.File; import java.util.Date; import java.util.Properties; import javax.mail.Authenticator; import javax.mail.Message; 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; public class AttachementWithHtmlContent < public static void main(String[] args) < Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", "smtp.gmail.com"); props.put("mail.smtp.port", "587"); props.put("mail.debug", "true"); Session session = Session.getInstance(props, new Authenticator() < protected PasswordAuthentication getPasswordAuthentication() < return new PasswordAuthentication("arvindraivns06@gmail.com", "password"); >>); try < MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress("arvindraivns06@gmail.com")); msg.setRecipients(Message.RecipientType.TO, "arvindraivns02@gmail.com"); msg.setSubject("Html Test Mail with Attachement"); msg.setSentDate(new Date()); Multipart multipart = new MimeMultipart(); MimeBodyPart htmlPart = new MimeBodyPart(); String htmlContent = "&lthtml&gt&ltbody&gt&lth1&gtHtml Content&lt/h1&gt&lt/body&gt&lt/html&gt"; htmlPart.setContent(htmlContent, "text/html"); multipart.addBodyPart(htmlPart); MimeBodyPart attachementPart = new MimeBodyPart(); attachementPart.attachFile(new File("D:/cp/pic.jpg")); multipart.addBodyPart(attachementPart); msg.setContent(multipart); Transport.send(msg); System.out.println("---Done---"); >catch (Exception ex) < ex.printStackTrace(); >> >
------=_Part_0_1361188139.1424959832984-- . 250 2.0.0 OK 1424959843 kg2sm1118833pbc.72 - gsmtp QUIT 221 2.0.0 closing connection kg2sm1118833pbc.72 - gsmtp ---Done---

Источник

Java MailAPI Example – Send an Email via GMail SMTP (TLS Authentication)

Java MailAPI Example - Send an Email via GMail SMTP (TLS Authentication

In this Java Tutorial we will see how to send an email using GMail SMTP protocol in Java. I’m using JavaMail API v1.6.2. It is very robust solution available in the market.

Читайте также:  Таблицы

The JavaMail API provides a platform-independent and protocol-independent framework to build mail and messaging applications. The JavaMail API is available as an optional package for use with Java SE platform and is also included in the Java EE platform. The JavaMail 1.6.2 release contains several bug fixes and enhancements.

Are you getting this error?

Exception in thread "main" java.lang.NoClassDefFoundError: com/sun/mail/util/MailLogger at javax.mail.Session.initLogger(Session.java:227) at javax.mail.Session.(Session.java:212) at javax.mail.Session.getDefaultInstance(Session.java:315) . .

com.sun.mail.util.MailLogger is part of JavaMail API. It is already included in Enterprise Edition environment (EE), but it is not included in Standard Edition environment (SE).

If you are running your test, tests in SE environment which means what you have to bother about adding it manually to your classpath when running tests.

Solution:

If you have maven project then try adding below two dependencies to pom.xml file to avoid below error:

 javax.mail mail 1.5.0-b01  javax.mail javax.mail-api 1.6.2  

If you want to convert your project to Maven project to have pom.xml file then follow the tutorial.

Java Example:

package crunchify.com.tutorial; import java.util.Properties; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; /** * @author Crunchify.com * */ public class CrunchifyJavaMailExample < static Properties mailServerProperties; static Session getMailSession; static MimeMessage generateMailMessage; public static void main(String args[]) throws AddressException, MessagingException < generateAndSendEmail(); System.out.println("\n\n ===>Your Java Program has just sent an Email successfully. Check your email.."); > public static void generateAndSendEmail() throws AddressException, MessagingException < // Step1 System.out.println("\n 1st ===>setup Mail Server Properties.."); mailServerProperties = System.getProperties(); mailServerProperties.put("mail.smtp.port", "587"); mailServerProperties.put("mail.smtp.auth", "true"); mailServerProperties.put("mail.smtp.starttls.enable", "true"); System.out.println("Mail Server Properties have been setup successfully.."); // Step2 System.out.println("\n\n 2nd ===> get Mail Session.."); getMailSession = Session.getDefaultInstance(mailServerProperties, null); generateMailMessage = new MimeMessage(getMailSession); generateMailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress("test1@crunchify.com")); generateMailMessage.addRecipient(Message.RecipientType.CC, new InternetAddress("test2@crunchify.com")); generateMailMessage.setSubject("Greetings from Crunchify.."); String emailBody = "Test email by Crunchify.com JavaMail API example. " + "

Regards,
Crunchify Admin"; generateMailMessage.setContent(emailBody, "text/html"); System.out.println("Mail Session has been created successfully.."); // Step3 System.out.println("\n\n 3rd ===> Get Session and Send mail"); Transport transport = getMailSession.getTransport("smtp"); // Enter your correct gmail UserID and Password // if you have 2FA enabled then provide App Specific Password transport.connect("smtp.gmail.com", "", ""); transport.sendMessage(generateMailMessage, generateMailMessage.getAllRecipients()); transport.close(); > >
1st ===> setup Mail Server Properties.. Mail Server Properties have been setup successfully.. 2nd ===> get Mail Session.. Mail Session has been created successfully.. 3rd ===> Get Session and Send mail ===> Your Java Program has just sent an Email successfully. Check your email..

Email Sample:

Crunchify.com JavaMail API Example With 2 Factor Authentication Enabled

Getting error? How to triage an issue?

  • If you’ve turned on 2-Step Verification for your account, you might need to enter an App password.
  • Important : If you’re still having problems, visit http://www.google.com/accounts/DisplayUnlockCaptcha and sign in with your Gmail username and password. If necessary, enter the letters in the distorted picture.

If you liked this article, then please share it on social media. Have a question or suggestion? Please leave a comment to start the discussion. 👋

Читайте также:  Python print format integer

Источник

Sending Email Using Java GMail and SMTP

Demonstrates how to securely connect to GMail using Java SMTP classes found in Secure iNet Factory.

java gmail

Google allows GMail account users to access their account using any capable email client such as Microsoft Outlook, Apple Mail.app and others. For this to work GMail provides POP and IMAP access to these client applications so that they can access emails stored on GMail servers. In addition to this, GMail provides access to its SMTP server to allow these clients to send emails through it. In order to prevent abuse such as spamming and to provide increased security the GMail SMTP server requires that you connect using SMTP SSL and login using your account credentials prior to sending any mail. The purpose of this article is to demonstrate how to securely connect to the GMail SMTP server and send mail using a bit of Java code which make use of com.jscape.inet.smtpssl.SmtpSsl class found in Secure iNet Factory. The procedures in this article may also apply to other SMTP servers that provide secure SSL/TLS access.
Prerequisites
GMail account Secure
iNet Factory

Using SmtpSsl to Send Email via GMail SMTP Server The SmtpSsl class implements basic functionality of a secure SMTP client using SSL/TLS. It supports both implicit SSL/TLS on port 465 (default) and explicit SSL/TLS using STARTTLS command on port 25. Below is a Java code snippet that shows how to use SmtpSsl to connect to GMail using implicit SSL, authenticate and then send an email.

import com.jscape.inet.smtpssl.SmtpSsl;
import com.jscape.inet.email.EmailMessage;
// create a new SmtpSsl instance connecting securely via port 465 using implicit SSL
smtp = new SmtpSsl("smtp.gmail.com", 465);
// establish secure connection
// login using gmail account details
smtp.login(username, password);
EmailMessage message = new EmailMessage();
message.setSubject("Sending email via Gmail SMTP");
message.setBody("This is the body of the message");

Summary

This article demonstrates how straightforward and easy it is to connect to a secure SMTP server, in this case GMail, and then send an email.

References

Setting Up SFTP Public Key Authentication On The Command Line

SFTP allows you to authenticate clients using public keys, which means they won’t need a password. Learn how to set this up in the command line online. Read Article

Active vs. Passive FTP Simplified: Understanding FTP Ports

If there are problems connecting to your FTP Server, check your transfer mode. Let JSCAPE help you understand the difference in active & passive FTP. Read Article

Active-Active vs. Active-Passive High-Availability Clustering

The most commonly used high-availability clustering configurations are Active-Active and Active-Passive. Learn the difference between the two online! Read Article

Using Windows FTP Scripts To Automate File Transfers

Learn how to automate file transfers using Windows FTP scripts. This post explains what FTP scripts are and how to create simple scripts to transfer files. Read Article

Источник

Оцените статью