Wednesday 8 February 2012

Send email in java


how to send email in java

import java.util.Properties;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class

Mail

{

public static void main(String[] args) {
String[] to = { "example@example.com" };
String[] cc = { "example.example@example.com" };
String[] bcc = { "example@example.com" };
This is for google
Mail.sendMail("example@example.com", "example", to, cc, bcc,
"dont send spams",
"dont send spams..");
}

public synchronized static boolean sendMail(String userName, String passWord, String[] to,
String[] cc, String[] bcc, String subject, String text) {
String starttls = "true";
String auth = "true";
String port="465";
String host="smtp.gmail.com";
String socketFactoryClass="javax.net.ssl.SSLSocketFactory";
boolean debug=true;
String fallback="false";

Properties props = new Properties();
// Properties props=System.getProperties();
props.put("mail.smtp.user", userName);
props.put("mail.smtp.host", host);
if (!"".equals(port))
props.put("mail.smtp.port", port);
if (!"".equals(starttls))
props.put("mail.smtp.starttls.enable", starttls);
props.put("mail.smtp.auth", auth);
if (debug) {
props.put("mail.smtp.debug", "true");
} else {
props.put("mail.smtp.debug", "false");
}
if (!"".equals(port))
props.put("mail.smtp.socketFactory.port", port);
if (!"".equals(socketFactoryClass))
props.put("mail.smtp.socketFactory.class", socketFactoryClass);
if (!"".equals(fallback))
props.put("mail.smtp.socketFactory.fallback", fallback);

try {
Session session = Session.getDefaultInstance(props, null);
session.setDebug(debug);
MimeMessage msg = new MimeMessage(session);
msg.setText(text);
msg.setSubject(subject);
msg.setFrom(new InternetAddress("example@example.com"));
for (int i = 0; i < to.length; i++) {
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(
to[i]));
}
if (cc != null) {
for (int i = 0; i < cc.length; i++) {
msg.addRecipient(Message.RecipientType.CC,
new InternetAddress(cc[i]));
}
}
if (bcc != null) {
for (int i = 0; i < bcc.length; i++) {
msg.addRecipient(Message.RecipientType.BCC,
new InternetAddress(bcc[i]));
}
}
msg.saveChanges();
Transport transport = session.getTransport("smtp");
transport.connect(host, userName, passWord);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
return true;
} catch (Exception mex) {
mex.printStackTrace();
return false;
}
}

}

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...