Saturday, 30 August 2014

Sending Email using Gmail Server.

Java mail API provide support to send email using gmail server and other mail servers. This tutorial needs javax.mail.jar file. Following tutorial sends email using gmail server.




import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
import java.io.UnsupportedEncodingException;

public class SendMailFromGmailServer
{
public static void main(String [] args){
                //Sender and Reciever user
String emailTo="emailto@gmail.com";
String senderName="Rahul Sharma";
final String userId = "emailfrom@gmail.com";
final String password = "password";

// Set mail server detail...
Properties properties = new Properties();
properties.setProperty("mail.smtp.host", "smtp.gmail.com");
properties.setProperty("mail.smtp.port", "587");
properties.setProperty("mail.smtp.auth", "true");
properties.setProperty("mail.smtp.starttls.enable", "true");

// get authenticated.
Session session = Session.getInstance(properties,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userId, password);
}
});

// Composing message.   
try{
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(userId,senderName));

//Adding recipient.
message.addRecipient(Message.RecipientType.TO,new InternetAddress(emailTo));
message.setSubject("Email Subject");

//Creating message body.
BodyPart bodyPart1 = new MimeBodyPart();
bodyPart1.setText("Email body section content is here.");

//Attaching file.
MimeBodyPart bodyPart2 = new MimeBodyPart();
String filename = "C:\\1.48358393-20131211.pdf";
DataSource source = new FileDataSource(filename);
bodyPart2.setDataHandler(new DataHandler(source));
bodyPart2.setFileName(filename);

//Adding both bodypart to multipart.
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(bodyPart1);
multipart.addBodyPart(bodyPart2);

//Creating final message to send.
message.setContent(multipart );

//Sending message.
Transport.send(message);

System.out.println("Email sent to email Id : "+emailTo);

}catch (MessagingException ex){
ex.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}

No comments:

Post a Comment