Saturday, May 9, 2009

Send Java Mail

download the
activation.jar
mail.jar files and put it into u'r lib
/**
* SendApp.java
* Created on Mar 12, 2009 6:08:04 AM
*/
package mail;
import java.util.Date;

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 SendApp {

/**
* Using this function u can send mail
* @param smtpHost: u have to specify u'r smtp host here
* @param smtpPort: the smtp port number for gmail its 587
* @param from: from address
* @param urPassword: password of the sender for authentication
* @param to: to address
* @param subject: subject of the mail
* @param content: the message content
* @throws AddressException
* @throws MessagingException
*/
public static void send(String smtpHost, int smtpPort,
String from, String urPassword,String to,
String subject, String content)
throws AddressException, MessagingException {

// Create a mail session
java.util.Properties props = new java.util.Properties();
props=System.getProperties();
props.put("mail.smtp.host", smtpHost);
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtps.auth", "true");
Session session=Session.getInstance(props,null);
session.setDebug(true);

// Construct the message
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
msg.setSubject(subject);
msg.setText(content);
msg.setSentDate(new Date());
Transport tr = null;
tr = session.getTransport("smtp");
tr.connect(smtpHost,smtpPort,from, urPassword);
tr.sendMessage(msg, msg.getAllRecipients());

}

public static void main(String[] args) throws Exception {
// Send a test message
String smtpHost="smtp.gmail.com";
int smtpPort=587;
String from="test@testmail.com";
String urPasswd="testpass";
String to="test@gmail.com";
String subject="Tested and working fine";
String message="Hello, \n\n How are you ?";
send(smtpHost, smtpPort,from,urPasswd,to,subject,message );
}
}

No comments:

Post a Comment

LinkWithin

Related Posts with Thumbnails