在我的代码中实现电子邮件服务

时间:2013-03-08 14:28:27

标签: java jsp email javax.mail

我一直在尝试实现以下servlet代码来实现电子邮件工具,但我一直在使用此代码获取错误。请看看它......

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Properties;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
import javax.servlet.RequestDispatcher;

public class email extends HttpServlet {

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String to="amanmaheshwari25@gmail.com"; //emailID at which the mail is send

    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    Session session=null;

    try{
      Properties props = new Properties();
      props.put("mail.smtp.host", "smtp.gmail.com");
      props.put("mail.smtp.socketFactory.port", "465");
      props.put("mail.smtp.socketFactory.class",
                    "javax.net.ssl.SSLSocketFactory");
      props.put("mail.smtp.auth", "true");
      props.put("mail.smtp.port", "465");

       session = Session.getDefaultInstance(props,
       new javax.mail.Authenticator() {
       protected PasswordAuthentication getPasswordAuthentication() {
       return new PasswordAuthentication("cconatus.2011@gmail.com","password");//change accordingly
       }
      });}
        catch(Exception e)
        {out.println("error234");}
      try {
      MimeMessage message = new MimeMessage(session);
       message.setFrom(new InternetAddress("ccnatus.2011@gmail.com"));//change accordingly
       message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));
       message.setSubject("Pls find the message inside");
       String dd = "hey";
       message.setText(dd);

       //send message
       Transport.send(message);
       out.println("success");
           } 
      catch(Exception e)
            {out.println("error");}
      finally {            
                out.close();
            }
        }

我得到的输出是: 错误,即从最后一个捕获块 请尽快给出一些建议。

1 个答案:

答案 0 :(得分:1)

以下属性对我有用:

  

mail.transport.protocol = smtp

     

mail.smtp.host = smtp.gmail.com

     

mail.smtp.auth = true

     

mail.smtp.starttls.enable = true

     

mail.smtp.port = 587