Showing posts with label mail attachment. Show all posts
Showing posts with label mail attachment. Show all posts

Saturday, December 17, 2016

Send email with attachment which contains byte[] via java mail

Java Send Email Using Smtp Server


DataSource dataSource = new ByteArrayDataSource(bytes, "application/pdf");
MimeBodyPart pdfBodyPart = new MimeBodyPart();
pdfBodyPart.setDataHandler(new DataHandler(dataSource));
pdfBodyPart.setFileName("bankAdminReport.pdf");

Friday, October 10, 2014

Using Java Send Email Using Smtp Server(Html, Attachment, Embedded Image)

First download java mail api jar from: https://java.net/projects/javamail/pages/Home or here.
And add this to your project classpath.


package com.pritom;

import java.util.*;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;

/**
 * Created by pritom on 30/11/2016.
 */
public class SendEmailUsingSmtp {
    private static final String toAddress = "pritom@xxxxx.com";

    public static void main(String[] args) {
        google();
        //office();
        //bleep();
    }

    private static void google() {
        String host = "smtp.gmail.com";
        String port = "587";
        String userName = "xxxxx@gmail.com";
        String password = "xxxxx";
        send(host, port, userName, password);
    }

    private static void office() {
        String host = "smtp.office365.com";
        String port = "587";
        String userName = "xxxxx@office.com";
        String password = "xxxxx";
        send(host, port, userName, password);
    }

    private static void bleep() {
        String host = "bleep.xxxxx.com";
        String port = "587";
        String userName = "pritom@xxxxx.com";
        String password = "xxxxx";
        send(host, port, userName, password);
    }

    private static void send(String host, String port, String userName, String password) {
        String attachments = "attachments/Attachment_1.gif;"
                + "attachments/Attachment_2.pdf;"
                + "attachments/Attachment_3.txt;"
                + "attachments/Attachment_4.docx;"
                + "attachments/Attachment_5.jpg";


        Properties props = new Properties();
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.port", port);
        props.put("mail.smtp.auth", "true");
        props.put("https.protocols", "TLSv1,SSLv3,SSLv2Hello");
        props.put("com.sun.net.ssl.enableECC", "false");
        props.put("jsse.enableSNIExtension", "false");

        String subject = "Java send mail example - TLS Authentication";

        Session mailSession = Session.getInstance(props, new javax.mail.Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(userName, password);
            }
        });

        MimeMessage message = new MimeMessage(mailSession) {
            protected void updateMessageID() throws MessagingException {
                if (getHeader("Message-ID") == null)
                    super.updateMessageID();
            }
        };

        try {

            /* If failed to send email then fail report delivered to following email address */
            /* But remember not all smtp server allow use different email address */
            //props.put("mail.smtp.from", "pritomkucse@gmail.com");

            message.setFrom(new InternetAddress(userName, "Pritom Kumar", "UTF-8"));
            message.setReplyTo(InternetAddress.parse(userName, false));
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(toAddress, toAddress, "UTF-8"));

            message.setSentDate(new Date());
            message.setSubject(subject, "UTF-8");
            Multipart multipart = new MimeMultipart();

            BodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setContent("This is <b>message</b> body, pls see "
                    + "<i style='color: blue; font-size: 40px;'>attachments</i>", "text/html");
            multipart.addBodyPart(messageBodyPart);

            for( int i = 0; i < attachments.split(";").length; i++) {
                String fileName = attachments.split(";")[i];
                messageBodyPart = new MimeBodyPart();
                DataSource source = new FileDataSource(fileName);
                messageBodyPart.setDataHandler(new DataHandler(source));
                messageBodyPart.setFileName(source.getName());
                messageBodyPart.setHeader("Content-ID", "<CONTENT_" + i + ">");
                multipart.addBodyPart(messageBodyPart);
            }

            /* Some custom headers added to email */
            message.addHeader("header-1", "header-1-value");
            message.addHeader("header-2", "header-2-value");

            messageBodyPart = new MimeBodyPart();
            messageBodyPart.setContent("<h1>Attachments are added.</h1>Attached image as embedded:<br/>"
                    + "<img style='width: 50px;' src='cid:CONTENT_4'/>", "text/html");
            multipart.addBodyPart(messageBodyPart);

            message.setContent(multipart );
            println("Start sending email...");
            Transport.send(message);
            println("Mail sent with message ID=" + message.getMessageID());
        }
        catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private static void println(Object o) {
        System.out.println(o);
    }
}

Console output would be like following

Start sending email...
Mail sent with message ID=<2059904228.1.1477967571904.JavaMail.pritom@PRITOM-PC>

In my gmail inbox email would be render as follows:



Use following code block if you want to use SSL Authentication


props.put("mail.smtp.host", HOST);
props.put("mail.smtp.socketFactory.port", PORT);
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", PORT);