Pages

Tuesday, January 21, 2014

How To Send Email With A PDF File & Message Body Using Java Code

Java Code :

package com.example.com;

import java.util.Date;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
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;

import org.openbravo.base.session.OBPropertiesProvider;

public class EmailWithPDF {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        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");
        Session session = Session.getInstance(props,
                new javax.mail.Authenticator() {
                    @Override
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication("yourmail@gmail.com",
                                "yourpasswrd");
                    }
                });
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress("opetionalemailid@gmail.com"));

        message.setRecipients(Message.RecipientType.TO, "toadrres@anymail.com");
        message.setSubject("Campaign Invitation");
        BodyPart messageBodyPart1 = new MimeBodyPart();
        messageBodyPart1.setText("Dear User,"
                + "\n\nWe are conducting an event on Somthing and date on "
                + new Date()
                + ". \nPlease find attached venue details for this campaign."
                + ". \nPlease attend this Email." + "\n\nThanks and Regards"
                + "\nEmail Management");
        Multipart multipart = new MimeMultipart();
        String sourcepath = OBPropertiesProvider.getInstance()
                .getOpenbravoProperties().getProperty("attach.path");

        String fileAttachment = "path of ur pdf or any file";
        MimeBodyPart messageBodyPart = new MimeBodyPart();
        DataSource source = new FileDataSource(fileAttachment);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName("pdffile name.pdf");
        multipart.addBodyPart(messageBodyPart1);
        multipart.addBodyPart(messageBodyPart);
        message.setContent(multipart);
        Transport.send(message);
    }
}

2 comments: