Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class EmailUtility {
- public static void sendEmail(String host, String port, final String userName, final String password,
- String toAddress, String subject, String message) throws AddressException, MessagingException {
- // setting SMTP server properties
- Properties properties = new Properties();
- properties.put("mail.smtp.host", host);
- properties.put("mail.smtp.port", port);
- properties.put("mail.smtp.auth", "true");
- properties.put("mail.smtp.starttls.enable", "true");
- Session session = Session.getInstance(properties, new javax.mail.Authenticator() {
- protected PasswordAuthentication getPasswordAuthentication() {
- return new PasswordAuthentication(userName, password);
- }
- });
- // creates a new e-mail message
- Message msg = new MimeMessage(session);
- msg.setFrom(new InternetAddress(userName));
- InternetAddress[] toAddresses = { new InternetAddress(toAddress) };
- msg.setRecipients(Message.RecipientType.TO, toAddresses);
- msg.setSubject(subject);
- msg.setSentDate(new Date());
- msg.setText(message);
- // sending the e-mail
- Transport.send(msg);
- }
- <context-param>
- <param-name>host</param-name>
- <param-value>smtp.gmail.com</param-value>
- </context-param>
- <context-param>
- <param-name>port</param-name>
- <param-value>587</param-value>
- </context-param>
- <context-param>
- <param-name>user</param-name>
- <param-value>test.123@gmail.com</param-value>
- </context-param>
- <context-param>
- <param-name>pass</param-name>
- <param-value>12345698</param-value>
- </context-param>
- public void init() {
- // reading SMTP server setting from web.xml file
- ServletContext context = getServletContext();
- host = context.getInitParameter("host");
- port = context.getInitParameter("port");
- user = context.getInitParameter("user");
- pass = context.getInitParameter("pass");
- }
- protected void doPost(HttpServletRequest request,
- HttpServletResponse response) throws ServletException, IOException {
- // reading form fields
- String recipient = request.getParameter("recipient");
- String subject = request.getParameter("subject");
- String content = request.getParameter("content");
- System.out.println(recipient+" sub "+subject+" content "+content);
- String resultMessage = "";
- try {
- EmailUtility.sendEmail(host, port, user, pass, recipient, subject,
- content);
- resultMessage = "The e-mail was sent successfully";
- } catch (Exception ex) {
- ex.printStackTrace();
- resultMessage = "There were an error: " + ex.getMessage();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement