Saturday, September 5, 2009

Email Using JavaMail

avaMail, a technology from Java allows programmers to develop code that can send emails whether in plain text or HTML. Here’s a short easy code to send email to a recipient.



public static boolean send(String replyTo, String from_email, String to_email, String subject, String body, String type) {
boolean sent = false;
try {
Properties prop = new Properties();
prop.setProperty(”mail.smtp.localhost”, “localhost”);
prop.setProperty(”mail.smtp.port”, “25″);
Session session = Session.getDefaultInstance(prop);

Message msg = new MimeMessage(session);
msg.setSubject(subject);

InternetAddress from = new InternetAddress(from_email);
InternetAddress to = new InternetAddress(to_email);
msg.addRecipient(Message.RecipientType.TO, to);
msg.setFrom(from);

Multipart multipart = new MimeMultipart(”related”);

BodyPart htmlPart = new MimeBodyPart();
if (type.equals(”html”)) htmlPart.setContent(body, “text/html”);
else htmlPart.setContent(body, “text/plain”);

multipart.addBodyPart(htmlPart);
msg.setContent(multipart);

Transport transport = session.getTransport(”smtp”);
transport.connect(USERNAME, PASSWORD); // username, password to connect to smtp server
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();

} catch (Exception e) {
System.err.println(”[MailTool] send() : ” + e.getMessage());
e.printStackTrace();
}

return sent;
}





Notice the line that says transport.connect(USERNAME, PASSWORD);

That line is optional in case you have set your SMTP server for authentication before emails are sent out by the mail server. The method also provides the option to let you send the email as plain text or HTML. Just set the value to html if you want it to be sent as HTML.

No comments: