Friday 5 October 2012

Sending Attachment Mail using Java

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.MessagingException;
import javax.mail.Multipart;
import javax.mail.SendFailedException;
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 SendAttachMail {
    public static void main(String[] args) throws MessagingException {
        SendAttachMail s = new SendAttachMail();
       
    }

    public SendAttachMail() throws MessagingException {

        String host = "smtp.gmail.com";
       /***
        * Here you need to give password
        */
        String Password = "xxxxxxxxxxx";
       
       
        String from = "xxxxxxxxxxxxxxxxxxxxxxx";
        String toAddress = "xxxxxxxxxxxxxxxxxxxxx";
        //Need to give file path
        String filename = "F:/ex/RealUsage/build.xml";
        // Get system properties
        Properties props = System.getProperties();
        props.put("mail.smtp.host", host);
        props.put("mail.smtps.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        Session session = Session.getInstance(props, null);

        MimeMessage message = new MimeMessage(session);

        message.setFrom(new InternetAddress(from));

        message.setRecipients(Message.RecipientType.TO, toAddress);

        message.setSubject("JavaMail Attachment");

        BodyPart messageBodyPart = new MimeBodyPart();

        messageBodyPart.setText("Here's the file");

        Multipart multipart = new MimeMultipart();

        multipart.addBodyPart(messageBodyPart);

        messageBodyPart = new MimeBodyPart();

        DataSource source = new FileDataSource(filename);

        messageBodyPart.setDataHandler(new DataHandler(source));

        messageBodyPart.setFileName(filename);

        multipart.addBodyPart(messageBodyPart);

        message.setContent(multipart);

        try {
            Transport tr = session.getTransport("smtps");
            tr.connect(host, from, Password);
            tr.sendMessage(message, message.getAllRecipients());
            System.out.println("Mail Sent Successfully");
            tr.close();

        } catch (SendFailedException sfe) {

            System.out.println(sfe);
        }
    }

}

SendingMail using Java

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.Properties;

public class GmailSendEmailSSL {
    public static final String USERNAME = "xxxxxxxxxxxxxxxx";
    public static final String PASSWORD = "xxxxxxxxxxxxxxxx";

    public static void main(String[] args) throws Exception {
        //
        // Email information such as from, to, subject and contents.
        //
        String mailFrom = "xxxxxxxxxxxxxxxxxxxxxx";
        String mailTo = "xxxxxxxxxxxxxxxxxxxxxxxxxxx";
        String mailSubject = "TestReport";
        String mailText = "Please check enclosed TestReport";

        GmailSendEmailSSL gmail = new GmailSendEmailSSL();
        gmail.sendMail(mailFrom, mailTo, mailSubject, mailText);
    }

    private void sendMail(String mailFrom, String mailTo,
                          String mailSubject, String mailText)
            throws Exception {

        Properties config = createConfiguration();

        //
        // Creates a mail session. We need to supply username and
        // password for Gmail authentication.
        //
        Session session = Session.getInstance(config, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(
                        GmailSendEmailSSL.USERNAME,
                        GmailSendEmailSSL.PASSWORD
                );
            }
        });

        //
        // Creates email message
        //
        Message message = new MimeMessage(session);
        message.setSentDate(new Date());
        message.setFrom(new InternetAddress(mailFrom));
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(mailTo));
        message.setSubject(mailSubject);
        message.setText(mailText);

        //
        // Send a message
        //
        Transport.send(message);
    }

    private Properties createConfiguration() {
        return new Properties() {{
            put("mail.smtp.host", "smtp.gmail.com");
            put("mail.smtp.auth", "true");
            put("mail.smtp.port", "465");
            put("mail.smtp.socketFactory.port", "465");
            put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        }};
    }
}