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("", "");

Authenticator auth = new Authenticator() {

    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(""));
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse("", false));

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

Multipart multipart = new MimeMultipart();

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));

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

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: Logo

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s

%d bloggers like this: