Saturday, July 4, 2009

Sending mail from Java

This is a simple java class 4 sending mail


import java.util.Properties;

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

public class SendMail {

private String from;
private String to;
private String subject;
private String text;

public SendMail(String from, String to, String subject, String text){
this.from = from;
this.to = to;
this.subject = subject;
this.text = text;
}

public void send(){

Properties p
roperties = new Properties();
properties .put("mail.smtp.host", "smtp.gmail.com"); // host and smtp settings
properties .put("mail.smtp.port", "465"); // port settins

Session mailSession = Session.getDefaultInstance(
properties);
Message simpleMessage = new MimeMessage(mailSession);

InternetAddress fromAddress = null;
InternetAddress toAddress = null;
try {
fromAddress = new InternetAddress(from);
toAddress = new InternetAddress(to);
} catch (AddressException e) {
e.printStackTrace();
}

try {
simpleMessage.setFrom(fromAddress);
simpleMessage.setRecipient(RecipientType.TO, toAddress);
simpleMessage.setSubject(subject);
simpleMessage.setText(text);

Transport.send(simpleMessage);
} catch (MessagingException e) {
e.printStackTrace();
}
}
}

Test Class

public class SendMailTest {

public static void main(String[] args) {

String from = "xxx@gmail.com";
String to = "yyy@gmail.com";
String subject = "Test";
String message = "A newmessage";

SendMail sendMail = new SendMail(from, to, subject, message);
sendMail.send();
}
}


No comments:

Post a Comment