Sending email from Java code using JavaMail

I was recently asked if it’s possible to send an email with attachments using Java API.
I’ve done some research and googling and here it is. Maybe someone find it also usefull.

So here it is. With these few lines you can send email using JavaMail API:

Properties props = new Properties();
props.setProperty("mail.smtp.host", "smtp.someserver.com");

Authenticator auth = new Authenticator() {

    @Override
    protected PasswordAuthentication getPasswordAuthentication() {
        PasswordAuthentication pa = new PasswordAuthentication("username", "passwd");
        return pa;
    }
};

Session session = Session.getInstance(props, auth);
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("username@someserver.com"));
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse("someoneelse@someotherserver.com", false));
msg.setSubject("Subject1");

MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText("some test message body");

Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);

File file = new File("/tmp/test_file.txt");
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));

messageBodyPart = new MimeBodyPart();
DataSource source = new ByteArrayDataSource(bis, "text/plain");
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName("test_file.txt");
multipart.addBodyPart(messageBodyPart);

msg.setContent(multipart);
msg.setSentDate(new Date());
msg.saveChanges(); // implicit with send()
Transport transport = session.getTransport("smtp");
transport.connect("smtp.someserver.com", "username", "passwd");
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
Advertisements

One Response to Sending email from Java code using JavaMail

  1. Pingback: JavaPins

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: