Tuesday, November 26, 2013

Sending Email using JavaMail API

In this post i am going to provide source code for sending email from our java application. There can be many cases when you may need to send email from your application. JavaMail API is used for sending email from java application.

Below code demonstrate how to send email from your Gmail account using JavaMail API. You can edit the source code for sending email from your desired email provider, for doing this you will need to provide smtp host and smtp port for your email provider. Replace the smtphost and smtpPort in the program.

Note: replace username , pass and to with your account’s username, password and to with the email address you want to send email.

You can Download JavaMail API from this link

/**
* SendMail class Demonstrate using JavaMail API to send email
* The code uses gmail account as sender account, you can use any email provider.
* set smtphost and smtpPort for the desired email provider.
*
* Replace username and pass with your account's username and password.
* Replace toAddress with the email address to whom you want to send email.
*/

import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;

class SendMail
{
String smtphost = "smtp.gmail.com";
String smtpPort ="587";

Session session;
MimeMessage message1;

String username = "your_email_id@host.com";
String pass = "your_pwd";
String to ="toAddress";

public static void main(String args[])
{
SendMail sm = new SendMail();
sm.createMessage();
sm.sendMail(to,"thisissubject","thisismessage");
}

public void createMessage()
{
try
{

//smtp properties
Properties prop = new Properties();
prop.put("mail.smtp.starttls.enable", "true");
prop.put("mail.smtp.host", smtphost);
prop.put("mail.smtp.user", username);
prop.put("mail.smtp.password", pass);
prop.put("mail.smtp.port", smtpPort);
prop.put("mail.smtp.auth", "true");

session = Session.getDefaultInstance(prop);

message1 = new MimeMessage(session);


}
catch(Exception e)
{
System.out.println("Connetction "+e);
}


}

//send mail method
public void sendMail(String receiptentAddress,String Subject,String messageText)
{
//counstructor will be called
String sendto = receiptentAddress;
String msg = messageText;
String sub = Subject;
String frm = username;
String pas = pass;

try
{
message1.setFrom(new InternetAddress(frm));

message1.addRecipient(Message.RecipientType.TO, new InternetAddress (sendto));

message1.setSubject(sub);

message1.setText(msg);

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

transport.connect(smtphost, frm, pas);
System.out.println("Sending mail..");
transport.sendMessage(message1, message1.getAllRecipients());

transport.close();

System.out.println("Sent!");

}catch(Exception e)
{
System.out.println(e);
}
}
}


No comments:

Post a Comment