37 sites, 19,917 entries and counting...     Get a free blog; Join a Weblog Network!
Top

Email Using JavaMail

January 8, 2009

JavaMail, 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.

Comments

One Response to “Email Using JavaMail”

  1. Benny Bottema on May 1st, 2009 4:50 am

    Also be sure to check out Vesijama, an open source JavaMail smtp API wrapper library. Vesijama stands for Very Simple Java Mail and is essentially a greatly simplifying wrapper to send emails of any complexity (it is designed to not bother you with RFC’s).

Got something to say?





Renegade Motorhomes - Credit Card Consolidation - Debt Consolidation - Credit Consolidation
Bottom