Code and Coffee


Sending an Email in Java

Posted on November 20, 2006, under Development.

Sending an email is a very common task in developing an application. You can send notifications, subscription notices, new comment notices, password changes, and the list goes on and on. Java has great API’s that allow you to easily send an email within a Java application. Below is a common function that I use in several Java applications to send an email. You have the option to set the server, username, password, array list of recipients , subject, message, and X-Mailer. This code snippet assumes you have a SMTP server that requires authentication to send mail, as mail servers these days do require authentication so that spammers do not abuse their servers.

[java]
// Imports
import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties;
import java.util.Date;

// Email
public boolean email(String strServer, String strUsername, String strPassword, ArrayList lTo, String strSubject, String strMessage, String strXMailer)
{
// Declare variables
Properties pProp = new Properties();
Session sMail = null;
Transport tMail = null;
MimeMessage mMessage = null;

// Set properties
pProp.setProperty(”mail.transport.protocol”, “smtp”);
pProp.setProperty(”mail.host”, strServer);
pProp.setProperty(”mail.user”, strUsername);
pProp.setProperty(”mail.password”, strPassword);
pProp.setProperty(”mail.from”, strUsername);

try
{
// Make session
sMail = Session.getInstance(pProp, null);

// Make transport
tMail = sMail.getTransport();

// Message
mMessage = new MimeMessage(sMail);
// — Subject
mMessage.setSubject(strSubject);
// — Body
mMessage.setText(strMessage);
// — Set X-Mailer
mMessage.setHeader(”X-Mailer”, strXMailer);
// — Set date
mMessage.setSentDate(new Date());
// — Set from
mMessage.setFrom(new InternetAddress(strUsername));
// — Address
for (int i = 0; i < lTo.size(); i++)
{
mMessage.addRecipient(Message.RecipientType.TO, new InternetAddress((String) lTo.get(i)));
}

// Connect
tMail.connect();

// Send
tMail.sendMessage(mMessage, mMessage.getRecipients(Message.RecipientType.TO));
}
catch (Exception eError)
{
return false;
}
finally
{
// Close
try
{
if (tMail != null)
tMail.close();
}
catch (MessagingException eError)
{
}
}

return true;
}

[/java]

Popularity: 4% [?]