Facebook Twitter Instagram
    TecAdmin
    • Home
    • Ubuntu 20.04
      • Upgrade Ubuntu
      • Install Java
      • Install Node.js
      • Install Docker
      • Install LAMP Stack
    • Tutorials
      • AWS
      • Shell Scripting
      • Docker
      • Git
      • MongoDB
    • FeedBack
    • Submit Article
    • About Us
    Facebook Twitter Instagram
    TecAdmin
    Home»Programming»JAVA»JavaMail API – Sending Email using Java from Gmail SMTP

    JavaMail API – Sending Email using Java from Gmail SMTP

    RahulBy RahulMay 24, 20142 Mins Read

    JavaMail API supports the JavaMail (javax.mail) interface for sending email messages. It provides classes for sending email from remote smtp server with authentication like Gmail, sendgrid etc.

    In this article we are using JavaMail API for sending emails using Java programming language through remote smtp server. This articles example are using Gmail smtp server as a remote smtp server for sending emails.

    Step 1: Setup JavaMail Environment

    First we need to download jar file containing all classes in javax.mail. Download jar (mail.jar) file from oracle official website.

    Now set the classpath in system environment. Windows users make sure you have configured PATH variable for your Java installation.

    Windows:

    c:> set classpath=mail.jar;.;
    

    Linux:

    # export JAVA_HOME=/opt/jdk1.8.0_05/
    # export PATH=$PATH:$JAVA_HOME/bin
    # export CLASSPATH=$JAVA_HOME/jre/lib/ext:$JAVA_HOME/lib/tools.jar:mail.jar:.
    

    Step 2: Write a Java Program to Send Email

    Create a java file SendMail.java with the following content. In this script you need to change many setting as per your setup. This script can be used for sending email through TLS or SSL SMTP connection through Gmail smtp servers.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    import java.util.Properties;
    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;
    import javax.mail.internet.AddressException;
     
    public class SendMail {
     
    public static void main(String[] args) throws Exception{
     
    final String smtp_host = "smtp.gmail.com";
    final String smtp_username = "myuser@gmail.com";
    final String smtp_password = "_email_password_";
    final String smtp_connection = "TLS";  // Use 'TLS' or 'SSL' connection
     
    final String toEmail="recipient@example.com";
    final String fromEmail="sender@example.com";
     
    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
     
       if (smtp_connection.equals("TLS")) {
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.port", "587");
    } else{
    props.put("mail.smtp.socketFactory.port", "465");
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.port", "465");
    }
     
    Session session = Session.getInstance(props,
      new javax.mail.Authenticator() {
    protected PasswordAuthentication getPasswordAuthentication() {
    return new PasswordAuthentication(smtp_username, smtp_password);
    }
      });
     
    try {
    Message msg = new MimeMessage(session);
    msg.setFrom(new InternetAddress(fromEmail, "NoReply"));
    msg.addRecipient(Message.RecipientType.TO,
    new InternetAddress(toEmail, "Mr. Recipient"));
    msg.setSubject("Welcome To JavaMail API");
    msg.setText("JavaMail API Test - Sending email example through remote smtp server");
    Transport.send(msg);
    System.out.println("Email sent successfully...");
    } catch (AddressException e) {
    throw new RuntimeException(e);
    } catch (MessagingException e) {
    throw new RuntimeException(e);
    }
    }
    }

    Step 3: Execute Program to Send Email

    Finally we need to execute java program to send email. as we know that this happens in two steps, first to compile program and second to run it.

    # javac SendMail.java
    # java SendMail
    
    API Gmail Java JavaMail mail smtp
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email WhatsApp
    Previous ArticleJavaMail API – Sending Email using Java from Local SMTP
    Next Article How to Configure DHCP Server on CentOS/RHEL 7/6/5

    Related Posts

    How to Install JAVA on Ubuntu 22.04

    Updated:May 16, 20224 Mins Read

    Java HashMap – How to Get Value from Key

    Updated:April 6, 20222 Mins Read

    Java HashMap – How to Get Key from Value

    Updated:April 6, 20222 Mins Read

    5 Methods to Print an Array in Java

    Updated:April 21, 20222 Mins Read

    How To Install Java on Debian 11

    4 Mins Read

    How to Install Roundcube Webmail on Ubuntu 20.04

    5 Mins Read

    2 Comments

    1. Ivan on September 23, 2019 9:25 pm

      This post is great. I checked out your blog site pretty regularly, and you’re
      always coming up with some great staff. I shared this post on my
      Twitter, and my followers loved it! To the
      next. Cheers.

      Reply
    2. Anshul Verma on October 23, 2015 6:12 pm

      sir getting this exception !!
      plz help
      run:
      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.getInstance(Session.java:248)
      at testing.SendMail.main(SendMail.java:41)
      Caused by: java.lang.ClassNotFoundException: com.sun.mail.util.MailLogger
      at java.net.URLClassLoader$1.run(URLClassLoader.java:372)
      at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
      at java.security.AccessController.doPrivileged(Native Method)
      at java.net.URLClassLoader.findClass(URLClassLoader.java:360)
      at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
      at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
      at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
      … 4 more
      Java Result: 1
      BUILD SUCCESSFUL (total time: 0 seconds)

      Reply

    Leave A Reply Cancel Reply

    Recent Posts
    • How to Install Ionic Framework on Ubuntu 22.04
    • What is the /etc/hosts file in Linux
    • How to Install Angular CLI on Ubuntu 22.04
    • How to Install Composer on Ubuntu 22.04
    • How to Create DMARC Record For Your Domain
    Facebook Twitter Instagram Pinterest
    © 2022 Tecadmin.net. All Rights Reserved | Terms  | Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.