Go to >> Java Code Samples
1.How to send a simple email in java
2.How to authenticate user and send email in java
1.How to send a simple email in java
package email;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class EmailExample {
public static void main(String[] args) {
EmailExample.sendEmail("mail.test.com", "121",
"webmaster@test.com", "to@test.com",
"Wazz up!", "Testing...");
}
public static void sendEmail(String smtpHost, String smtpPort
, String from, String to, String subject, String body) {
Properties props = System.getProperties();
props.put("mail.smtp.host", smtpHost);
props.put("mail.smtp.port", smtpPort);
Session session = Session.getInstance(props, null);
MimeMessage message = new MimeMessage(session);
try {
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject(subject);
message.setText(body);
Transport.send(message);
} catch (MessagingException ex) {
System.err.println("Opps!! could not send email. " + ex);
}
}
}
2.How to authenticate user and send email in java
package basics;
import java.util.Date;
import java.util.Map;
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.apache.log4j.Logger;
/**
* This is a default mail sender instance, which is implemented based on
* javax.mail API. This handles the actual mail sending part.
* The caller should create a map of email parameters and pass it to
* the send(Map) method.
*
* Map<String, String> params = new HashMap<String, String>();
* params.put(Mail.SMTP_HOST, "smtp.blogspot.test.com"));
* params.put(Mail.FROM, "testz_apps@blogger.test.com");
* params.put(Mail.TO, "testz_apps@blogger.test.com");
* params.put(Mail.SUBJECT, "");
* params.put(Mail.BODY, "");
* mailSender.send(params);
*
* It supports only "text/plain" as body content. When there are multiple
* emails concatenated in one String for Mail.TO,Mail.CC or
* Mail.BCC, use ',' as a separator or use Mail.ADDRESS_SEPERATOR instead.
* If the credentials need to be authenticated, a Mail.AUTH parameter
* should be set in the parameters map with the value of "true" along
* with Mail.USER_NAME and Mail.PASSWORD params.
*
* Map<String, String> params = new HashMap<String, String>();
* params.put(Mail.SMTP_HOST, "smtp.blogspot.test.com"));
* params.put(Mail.FROM, "testz_apps@blogger.test.com");
* params.put(Mail.TO, "testz_apps@blogger.test.com");
* params.put(Mail.SUBJECT, "");
* params.put(Mail.BODY, "");
* params.put(AUTH, "true");
* params.put(USER_NAME, "kannan");
* params.put(PASSWORD, "password");
* mailSender.send(params);
*
* @author Kannan
* @version 1.0
*/
public class MailSender implements IMailSender {
// TODO Implement replyTo
// TODO Implement files attachment
// TODO Implement template content
/** The log handler. */
private Logger logger = Logger.getLogger(this.getClass().getName());
/**
* {@inheritDoc}
*/
public boolean send(Map mailParams) throws EmailSendException {
boolean result = false;
try {
// validate the mandatory parameters, and throws the EmailSendException.
validateParams(mailParams);
// Sends the mail if the validation is fine.
sendMail(mailParams);
result = true;
if (logger.isDebugEnabled()) {
logger.debug("mails sent successfully");
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new EmailSendException(e.getMessage());
}
return result;
}
/**
* Validates all parameters. The to address, from address, body, subject
* and smtp host address parameters are mandatory. if one of mandatory
* parameters is null or one of to address, from address and smtp host
* address is empty, then it throws the EmailSendException with a
* appropriate message.
*
* @param mailParams the mail parameters.
* @throws if one of mandatory parameters is null
* @throws EmailSendException the email send exception
*/
private void validateParams(Map mailParams) throws EmailSendException {
if (mailParams == null) {
logger.error("The mail parameter map is null");
throw new EmailSendException("The mail parameter map is null");
}
// validates the smtp host address, the smtp host can not be empty.
String smtpHost = (String) mailParams.get(SMTP_HOST);
if (smtpHost == null || smtpHost.equals("")) {
logger.error("The mail smtp host is null or empty");
throw new EmailSendException("The mail smtp host is null or empty");
}
// validates the from address, the from address can not be empty.
String from = (String) mailParams.get(FROM);
if (from == null || from.equals("")) {
logger.error("The mail from address is null or empty");
throw new EmailSendException("The mail from address is null or empty");
}
// validates the subject, the subject can be empty.
String subject = (String) mailParams.get(SUBJECT);
if (subject == null) {
logger.error("The mail subject is null");
throw new EmailSendException("The mail subject is null");
}
// validates the body, the body can be empty.
String body = (String) mailParams.get(BODY);
if (body == null) {
logger.error("The mail body is null");
throw new EmailSendException("The mail body is null");
}
// validates the to address, the to address can not be empty.
String to = (String) mailParams.get(TO);
if (to == null || to.equals("")) {
logger.error("The mail to address is null or empty");
throw new EmailSendException("The mail to address is null or empty");
}
}
/**
* Sends the email for given toAddress. The message body and subject will be
* messageBody and messageSubject.
*
* @param mailParams the mail params
* @throws AddressException throws when a wrongly formatted address is encountered.
* @throws MessagingException if there are any other unexpected exception is encountered
* @throws EmailSendException the email send exception
*/
private void sendMail(Map mailParams) throws EmailSendException {
String from = (String) mailParams.get(FROM);
String subject = (String) mailParams.get(SUBJECT);
String body = (String) mailParams.get(BODY);
String to = (String) mailParams.get(TO);
String cc = (String) mailParams.get(CC);
String bcc = (String) mailParams.get(BCC);
String smtpHost = (String) mailParams.get(SMTP_HOST);
String smtpPort = (String) mailParams.get(SMTP_PORT);
String auth = (String) mailParams.get(AUTH);
// Get system properties
Properties props = System.getProperties();
// Specify the desired SMTP server
props.put("mail.smtp.host", smtpHost);
if (smtpPort != null) {// if null, the default port 25 will be used instead
props.put("mail.smtp.port", smtpPort);
}
// Create a new Session object
Session session = null;
// If authentication is required
if (auth != null && auth.toLowerCase().equals("true")) {
String username = (String) mailParams.get(USER_NAME);
String password = (String) mailParams.get(PASSWORD);
SMTPAuthenticator authenticator = new SMTPAuthenticator(username, password);
session = Session.getInstance(props, authenticator);
} else {
// If authentication is not required
session = Session.getInstance(props, null);
}
// Create a new MimeMessage object (using the Session created above)
Message message = new MimeMessage(session);
try {
// Setting the from address
message.setFrom(new InternetAddress(from));
// Setting the CC address if it's not null and empty
message.setRecipients(Message.RecipientType.TO, getInternetAddress(to));
if (cc != null && !cc.equals("")) {
message.setRecipients(Message.RecipientType.CC, getInternetAddress(cc));
}
// Setting the BCC address if it's not null and empty
if (bcc != null && !bcc.equals("")) {
message.setRecipients(Message.RecipientType.BCC, getInternetAddress(bcc));
}
// Setting the subject and body content. it supports only "text/plain" for now.
message.setSubject(subject);
message.setSentDate(new Date());
message.setContent(body, "text/plain");
if (logger.isDebugEnabled()) {
logger.debug("The mail is going to be sent using the following parameters");
logger.debug("To : " + to);
logger.debug("From : " + from);
logger.debug("Subject : " + subject);
logger.debug("Body : " + body);
logger.debug("Smtp host : " + smtpHost);
logger.debug("CC : " + cc);
logger.debug("BCC : " + bcc);
}
Transport.send(message);
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new EmailSendException(e.getMessage(), e);
}
}
/**
* Returns the array ofInternetAddress
, for given address. it splits the give
* address with theADDRESS_SEPERATOR
and convert it into a
*InternetAddress
.
*
* @param address the address, can be a single address or multiple address separated by
*ADDRESS_SEPERATOR
.
* @return the array ofInternetAddress
, for given address
* @throws EmailSendException if there are anyAddressException
, then it logs the
* error and wraps it withEmailSendException
and then throws it.
*/
private InternetAddress[] getInternetAddress(String address) throws EmailSendException {
String addressArray[] = address.split(ADDRESS_SEPERATOR);
InternetAddress[] inetAddress = new InternetAddress[addressArray.length];
for (int i = 0; i < addressArray.length; i++) {
try {
inetAddress[i] = new InternetAddress(addressArray[i]);
} catch (AddressException e) {
logger.error(e.getMessage(), e);
throw new EmailSendException(e.getMessage(), e);
}
}
return inetAddress;
}
/**
* The Class SMTPAuthenticator.
*/
private class SMTPAuthenticator extends javax.mail.Authenticator {
/** The username. */
String username = null;
/** The password. */
String password = null;
/**
* Instantiates a new sMTP authenticator.
*
* @param username the username
* @param password the password
*/
SMTPAuthenticator(String username, String password) {
this.username = username;
this.password = password;
}
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
}
}
/**
* The constant class holds the key value pair.
*
* @author Kannan
* @version 1.0
*/
public class Mail {
/** The email address separator */
public static final String ADDRESS_SEPERATOR = ",";
/** The key for email from address */
public static final String FROM = "FROM";
/** The key for email subject address */
public static final String SUBJECT = "SUBJECT";
/** The key for email body address */
public static final String BODY = "BODY";
/** The key for email SMTP address */
public static final String SMTP_HOST = "SMTP_HOST";
/** The key for email SMTP port */
public static final String SMTP_PORT = "SMTP_PORT";
/** The key for email to address */
public static final String TO = "TO";
/** The key for email CC address */
public static final String CC = "CC";
/** The key for email BCC address */
public static final String BCC = "BCC";
/** The key for username */
public static final String USER_NAME = "USER_NAME";
/** The key for password */
public static final String PASSWORD = "PASSWORD";
/** The key for email authentication indicator */
public static final String AUTH = "AUTH";
}
/**
* The interface define methods for sending mails.
*
* @author Kannan
* @version 1.0
*/
public interface IMailSender {
/**
* Send the mail according to the parameters that are set by themailParams
map.
*
* @param the mail parameters. the mail parameters can be set as follows. *
*
* Map<String, String> params = new HashMap<String, String>();
* params.put(Mail.SMTP_HOST, "smtp.blogspot.test.com"));
* params.put(Mail.FROM, "testz_apps@blogger.test.com");
* params.put(Mail.TO, "testz_apps@blogger.test.com");
* params.put(Mail.SUBJECT, "");
* params.put(Mail.BODY, "");
* mailSender.send(params);
*
* @throws EmailSendException, if there are any exceptions conditions, then it is wrapped with
*EmailSendException
and thrown.
*/
boolean send(Map mailParams) throws EmailSendException;
}
No comments:
Post a Comment