Send email from servlet using java mail

package mailpack;

import java.io.IOException;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class send extends HttpServlet {
private static final long serialVersionUID = 1L;

public send() {
// TODO Auto-generated constructor stub
}

protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}

protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException

{
System.out.println(“Entered.. into servlet”);
Properties props = new Properties();

props.put(constants.SMTPS_HOST_KEY, constants.SMTPS_GMAIL_HOST);
props.put(constants.SMTPS_AUTH_KEY, constants.TRUE_VALUE);
props.put(“mail.smtp.port”, constants.PORT);
props.setProperty(“mail.smtp.socketFactory.port”, constants.PORT);
props.setProperty(“mail.smtp.socketFactory.class”, “javax.net.ssl.SSLSocketFactory”);

Session session = Session.getInstance(props,new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(constants.FROM_USERNAME, constants.FROM_USER_PASSWORD);
}
 });
//Transport transport;
try {
System.out.println(“Trying to send mail”);
//transport = session.getTransport(constants.TRANSPORT_PROTOCOL);
//transport.connect(constants.FROM_USERNAME,constants.FROM_USER_PASSWORD);

Message msg = new MimeMessage(session);
MimeMultipart content = new MimeMultipart(
constants.MULTIPART_SUBTYPE);

// HTML part
MimeBodyPart textPart = new MimeBodyPart();
content.addBodyPart(textPart);
msg.setSubject(constants.EMAIL_SUBJECT);
//msg.setContent(content);
msg.setText(“Hello World, Mail Test”);
msg.setFrom(new InternetAddress(constants.FROM_EMAIL_ADDRESS));

String toEmail = “mailID@gmail.com”;
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(toEmail));
Transport.send(msg);

System.out.println(“message sent !!”);
} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *

Enable Notifications OK No thanks