Saturday, 30 August 2014

Sending Email using mail server credential like IP or Host, Port, User and Password.

Java provide a mail API that supports mail working like sending and checking mail. This tutorial needs javax.mail.jar file.

Following tutorial sends email using a particular mail server details.

import java.util.Properties;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class SendMail {

public static void main(String[] args) {

String sendTo = "sendto@gmail.com";
String From = "noreply@blogspot.com";
String user="userName";
String password="password";
String senderName="rahul sharma";
Session session=null;
String host="30.140.200.100";//temporary address
String port="25";
String subject ="Test Mail";
String message="This is test mail.";
try{
//Setting authentication properties
Properties properties = new Properties();
properties.setProperty("mail.smtp.host", host);
properties.setProperty("mail.smtp.port", port);
properties.setProperty("mail.user", user);
properties.setProperty("mail.password", password);
           
// Creating Session object.
session = Session.getInstance(properties, null);

//Creating message and set addresses.
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(From,senderName));
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(sendTo));
msg.setSubject(subject);

//Creating Body parts.
MimeBodyPart mbp1 = new MimeBodyPart();
mbp1.setText(message);
mbp1.setContent(message,"text/html");

//attaching body parts.
Multipart mp = new MimeMultipart();
mp.addBodyPart(mbp1);
msg.setContent(mp);

//sending mail.
Transport.send(msg);

System.out.println("Email sent to ......"+sendTo);

}catch(AddressException ae) {
ae.printStackTrace();
}catch(MessagingException me) {
me.printStackTrace();
}catch(Exception e) {
e.printStackTrace();
}
}
}

No comments:

Post a Comment