servlets sending email

You can send email from a Servlet using the JavaMail API. Here's an example of a Servlet that sends an email using Gmail SMTP server:

@WebServlet("/sendmail")
public class SendMailServlet extends HttpServlet {
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String to = request.getParameter("to");
    String subject = request.getParameter("subject");
    String message = request.getParameter("message");

    final String username = "[email protected]";
    final String password = "yourgmailpassword";

    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.port", "587");

    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
      protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(username, password);
      }
    });

    try {
      Message msg = new MimeMessage(session);
      msg.setFrom(new InternetAddress(username));
      msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
      msg.setSubject(subject);
      msg.setText(message);
      Transport.send(msg);
      response.getWriter().println("Email sent successfully.");
    } catch (MessagingException e) {
      response.getWriter().println("Failed to send email: " + e.getMessage());
    }
  }
}
Source‮.www:‬theitroad.com

In this example, the Servlet retrieves the email parameters from the HttpServletRequest object using the getParameter method.

The Servlet then sets up the email configuration by creating a Properties object with the SMTP server settings. The javax.mail.Authenticator class is used to authenticate the user with the SMTP server.

The Servlet then creates a Session object with the email configuration and authenticator, and constructs the email message using the MimeMessage class. The message is then sent using the Transport class.

If the email is sent successfully, the Servlet sends a response to the client indicating success. If there is an error sending the email, the Servlet sends an error message to the client.

Note that you will need to have the JavaMail API library in your classpath in order to use this code. Also, be sure to use a secure password and keep it safe, as the password is stored in plaintext in the Servlet code.