Send email to gmail with SSL - Java Network

Java examples for Network:EMail

Description

Send email to gmail with SSL

Demo Code

/* Use mail-1.4.1.jar */

import java.io.File;
import java.util.Date;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
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 MailTest {

    public static void main(String[] args) {

        /*Different Hosts :
          Gmail : Host :  smtp.gmail.com    Port : 587 (TLS Port)  -> props.put("mail.smtp.starttls.enable", "true")
          Yahoo : Host :  smtp.mail.yahoo.com    Port : 465 (SSL Port)
          Outlook : Host  :  smtp-mail.outlook.com     Port : 587
         *///from   w  ww  . j av a2 s . c  o  m

        String host = "smtp-mail.outlook.com";
        String port = "587"; //465,25, 587
        String username = "from@outlook.com";
        String password = "XYZ";
        String to = "to@outlook.com";
        String filename = "abc.txt";
        String path = "C:/mailtest"; // For file C:/mailtest/abc.txt
        Properties props = System.getProperties();
        props.setProperty("mail.smtp.host", host);
        props.setProperty("mail.smtp.port", port);
        final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
        //props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);  // For SSL
        //props.setProperty("mail.smtp.socketFactory.fallback", "false");  // For SSL
        //props.setProperty("mail.smtp.socketFactory.port", port);    // For SSL
        props.put("mail.smtp.auth", "true"); // For authentication
        props.put("mail.debug", "true"); // This is optional. This is for debug looger.
        props.put("mail.store.protocol", "pop3");
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.starttls.enable", "true"); // Use this for TLS

        try {
            Session session = Session.getDefaultInstance(props,
                    new Authenticator() {
                        protected PasswordAuthentication getPasswordAuthentication() {
                            return new PasswordAuthentication(username,
                                    password);
                        }
                    });

            // -- Create a new message --
            Message msg = new MimeMessage(session);
            msg.addHeader("Content-type", "text/HTML; charset=UTF-8");
            msg.addHeader("format", "flowed");
            msg.addHeader("Content-Transfer-Encoding", "8bit");
            // -- Set the FROM and TO fields --
            msg.setFrom(new InternetAddress(username));
            msg.setRecipients(Message.RecipientType.TO,
                    InternetAddress.parse(to, false));
            msg.setSubject("Hello");
            //msg.setText("How are you");
            msg.setSentDate(new Date());

            // Create the message body part with attachments
            BodyPart messageBodyPart = new MimeBodyPart();
            // Fill the message
            messageBodyPart.setText("This is mail with attachments.");
            // Create a multipart message for attachment
            Multipart multipart = new MimeMultipart();
            // Set text message part
            multipart.addBodyPart(messageBodyPart);
            // Second part is attachment
            messageBodyPart = new MimeBodyPart();
            try {
                File att = new File(new File(path), filename);
                ((MimeBodyPart) messageBodyPart).attachFile(att);
                multipart.addBodyPart(messageBodyPart);
            } catch (Exception e) {
                System.out.println(e);
            }

            // To attach image
            String image = "mypic.jpg"; // PAth : C:/mailtet/mypic.jpg
            messageBodyPart = new MimeBodyPart();
            try {
                File att1 = new File(new File(path), image);
                ((MimeBodyPart) messageBodyPart).attachFile(att1);
                messageBodyPart.setHeader("Content-ID", "image_id");
                multipart.addBodyPart(messageBodyPart);
            } catch (Exception e) {
                System.out.println(e);
            }
            //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);*/

            // Send the complete message parts
            msg.setContent(multipart);

            Transport.send(msg);
            System.out.println("Message sent.");
        } catch (MessagingException e) {
            System.out.println("Error : " + e);
        }
    }
}

Related Tutorials