Pages Navigation Menu

Coding is much easier than you think

Sending email with attachment using JavaMail API

Posted by on Jun 15, 2013 in Java | 0 comments

Sending email with attachment
 
In previous article, we have implemented a program to send Email through Gmail server in Java, In this article we shall learnt to implement a program to send email with attachment using JavaMail API.
 
For sending email with attachment, JavaMail API provides some useful classes like BodyPart, MimeBodyPart etc.
 

For sending email using JavaMail Api you need to import 2 jar files:

1.mail.jar
2.activation.jar

Download required jar files here..
download

There are total 7 steps for sending attachment with email. They are: 

1. Get the session object
2. Compose message
3. Create MimeBodyPart object and set your message text
4. Create new MimeBodyPart object and set DataHandler object to this object
5. Create Multipart object and add MimeBodyPart objects to this object
6. Set the multiplart object to the message object
7. Send message

 

package com.simplecode.email;

import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;

import javax.mail.Session;
import javax.mail.Message;
import javax.mail.BodyPart;
import javax.mail.Transport;
import javax.mail.Multipart;
import javax.mail.MessagingException;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.AddressException;

public class JavaEmailAttachment {

	Properties emailProperties;
	Session mailSession;
	MimeMessage message;
	// Create the message part
	BodyPart messageBodyPart;
	// Create message part for attaching file
	BodyPart messageFilePart;

	// Create a multipart message
	Multipart multipart;

	public static void main(String arg[]) throws AddressException,
			MessagingException {

		JavaEmailAttachment javaEmail = new JavaEmailAttachment();

		javaEmail.setMailServerProperties();
		javaEmail.createEmailMessage();
		javaEmail.sendEmail();
	}

	public void setMailServerProperties() {

		// gmail's smtp port
		String emailPort = "587";
		emailProperties = System.getProperties();
		emailProperties.put("mail.smtp.port", emailPort);
		emailProperties.put("mail.smtp.auth", "true");
		emailProperties.put("mail.smtp.starttls.enable", "true");
	}

	public void createEmailMessage() throws AddressException,
			MessagingException {
		String[] toEmails = { "to@gmail.com" };
		String emailSubject = "Java Email";
		String emailBody = "This is an email sent by JavaMail api";

		// 1. Get the session object
		mailSession = Session.getDefaultInstance(emailProperties, null);
		// 2. Compose message
		message = new MimeMessage(mailSession);

for (int i = 0; i < toEmails.length; i++) {
message.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmails[i]));
}

		message.setSubject(emailSubject);

		// 3. Create MimeBodyPart object and set your message text
		messageBodyPart = new MimeBodyPart();
		messageBodyPart.setText(emailBody);

		// 4. Create new MimeBodyPart object and set DataHandler object to this
		// object - for attachment

		messageFilePart = new MimeBodyPart();

		String filename = "JavaEmail.java";
		String fileloc = "C:/Users/Nisha/Desktop/JavaEmail.java";
		DataSource source = new FileDataSource(fileloc);
		messageFilePart.setDataHandler(new DataHandler(source));
		messageFilePart.setFileName(filename);

		// 5. Create Multipart object and add MimeBodyPart objects to this
		// object

		multipart = new MimeMultipart();

		// Set the body and file
		multipart.addBodyPart(messageBodyPart);
		multipart.addBodyPart(messageFilePart);

		// 6. set the multiplart object to the message object

		message.setContent(multipart);

	}

	public void sendEmail() throws AddressException, MessagingException {
		String emailHost = "smtp.gmail.com";

		// just the id alone without @ gmail.com
		String senderUsername = "your emailid here";
		String senderEmailPassword = "your email password here";

		// 7. send message

		Transport transport = mailSession.getTransport("smtp");

		transport.connect(emailHost, senderUsername, senderEmailPassword);
		transport.sendMessage(message, message.getAllRecipients());
		transport.close();
		System.out.println("Email sent successfully.");
	}

}
Read More

Sending Email through Gmail server in Java

Posted by on Jun 15, 2013 in Java | 0 comments

Email via Gmail

This java tutorial is to send email in java using Gmail. The program will use Gmail SMTP server to send mail.

For sending email using JavaMail Api you need to import 2 jar files:

1.mail.jar
2.activation.jar

Download required jar files here..
download

package com.simplecode.email;

import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class JavaEmail {

	Properties emailProperties;
	Session mailSession;
	MimeMessage message;

	public static void main(String args[]) throws AddressException,
			MessagingException {

		JavaEmail javaEmail = new JavaEmail();

		javaEmail.setMailServerProperties();
		javaEmail.createEmailMessage();
		javaEmail.sendEmail();
	}

	public void setMailServerProperties() {

		// gmail's smtp port
		String emailPort = "587";

		emailProperties = System.getProperties();
		emailProperties.put("mail.smtp.port", emailPort);
		emailProperties.put("mail.smtp.auth", "true");
		emailProperties.put("mail.smtp.starttls.enable", "true");

	}

	public void createEmailMessage() throws AddressException,
			MessagingException {
		String[] toEmails = { "to@gmail.com" };
		String emailSubject = "Java Email";
		String emailBody = "This is an email sent by <b>JavaMail</b> api.";

		mailSession = Session.getDefaultInstance(emailProperties, null);
		message = new MimeMessage(mailSession);

		for (int i = 0; i < toEmails.length; i++) {
	message.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmails[i]));
		}

		message.setSubject(emailSubject);
		// for a html email
		message.setContent(emailBody, "text/html");
		// emailMessage.setText(emailBody);// for a text email

	}

	public void sendEmail() throws AddressException, MessagingException {
		String emailHost = "smtp.gmail.com";

		// just the id alone without @ gmail.com
		String senderUsername = "your emailid here";
		String senderEmailPassword = "your email password here";

		Transport transport = mailSession.getTransport("smtp");
		transport.connect(emailHost, senderUsername, senderEmailPassword);
		transport.sendMessage(message, message.getAllRecipients());
		transport.close();
		System.out.println("Email sent successfully.");
	}

}
Note :

  • Here it is assumed that your localhost is connected to the internet and capable enough to send an email.
  • The example program uses Gmail SMTP server.
  • Mail authentication is set to true and need to give sender’s email and password. That is, we cannot send email anonymously.
  • You can add email attachment to emailMessage.
Read More