使用JavaMail API通过servlet发送的电子邮件无法通过

时间:2012-03-05 08:35:21

标签: java email servlets smtp javamail

以下是我的代码,它没有给我任何错误,但我的帐户中也没有收到该电子邮件。我浏览了有关此事的所有帖子并相应地修改了我的代码。我对这个事情很陌生,所以这个问题可能看起来很愚蠢,但仍然欢迎任何指示/建议。此外,servlet将在谷歌应用引擎上运行。我正在使用我的Gmail帐户用户名和密码而不是abc@gmail.com和密码。谢谢。

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.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class UserFeedback extends HttpServlet
{
public void doPost(HttpServletRequest req, HttpServletResponse res) 
{
    sendFeedback(req, res);
}

private void sendFeedback(HttpServletRequest req, HttpServletResponse res)
{
    String from = null, sub = null, msg = null;
    String host = "smtp.gmail.com", username = "abc@gmail.com", password = "password";
    Session session = null;
    MimeMessage email = null;
    Transport transport = null;

    sub = req.getParameter("subject");
    from = req.getParameter("sender");
    msg = req.getParameter("message");
    msg = "From: " + from + "\n" + msg;

    Properties props = System.getProperties();
    props.setProperty("mail.transport.protocol", "smtp");
    props.setProperty("mail.host", host);
    props.put("mail.smtp.user", username);
    props.put("mail.smtp.password", password);
    props.put("mail.smtp.port", "465");
    props.put("mail.smtp.auth", "true");
    props.put("mail.debug", "true");  
    props.put("mail.smtp.socketFactory.port", "465");  
    props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");  
    props.put("mail.smtp.socketFactory.fallback", "false");

    session = Session.getDefaultInstance(props, new javax.mail.Authenticator(){ protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("abc@gmail.com", "password");}});
    session.setDebug(true);

    email = new MimeMessage(session);
    try 
    {
        email.setSender(new InternetAddress(username));
        email.setRecipients(Message.RecipientType.TO, InternetAddress.parse("abc@gmail.com"));
        email.setSubject(sub);
        email.setContent(msg, "text/plain");
    }
    catch (AddressException e) 
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } 
    catch (MessagingException e) 
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    try 
    {
        Transport.send(email);
    } 
    catch (NoSuchProviderException e) 
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    catch (MessagingException e)
    {
        e.printStackTrace();
    }
}
 }

3 个答案:

答案 0 :(得分:0)

您应该使用JavaMail的许多Facade实现之一。将大大清理您的代码。

要查明此代码是否有效,请编写单元测试并使用:

这将为您快速找到答案

答案 1 :(得分:0)

您正在使用:

Properties props = System.getProperties();

请改用:

Properties props = new Properties();

如果它没有帮助发布显示已经发送电子邮件的服务器日志。

答案 2 :(得分:0)

这是一种发送邮件应用程序..... 它的静态应用程序,它的工作和我们从这个开发动态应用程序..所以尝试一次.. 添加此jar文件 dsn.jar,imap.jar,mailapi.jar和pop3.jar,smtp.jar。

package Javamail;
/*
Some SMTP servers require a username and password authentication before you
can use their Server for Sending mail. This is most common with couple
of ISP's who provide SMTP Address to Send Mail.

This Program gives any example on how to do SMTP Authentication
(User and Password verification)

This is a free source code and is provided as it is without any warranties and
it can be used in any your code for free.

*/

import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
import java.io.*;

/*
  To use this program, change values for the following three constants,
    SMTP_HOST_NAME -- Has your SMTP Host Name
    SMTP_AUTH_USER -- Has your SMTP Authentication UserName
    SMTP_AUTH_PWD  -- Has your SMTP Authentication Password
  Next change values for fields
  emailMsgTxt  -- Message Text for the Email
  emailSubjectTxt  -- Subject for email
  emailFromAddress -- Email Address whose name will appears as "from" address
  Next change value for "emailList".
  This String array has List of all Email Addresses to Email Email needs to be sent to.
  Next to run the program, execute it as follows,
  SendMailUsingAuthentication authProg = new SendMailUsingAuthentication();
*/

public class SendmailUsejavamail
{

  private static final String SMTP_HOST_NAME = "smtp.gmail.com";
  private static final String SMTP_AUTH_USER = "aaaa@gmail.com";
  private static final String SMTP_AUTH_PWD  = "xxxxxxxxx";

  private static final String emailMsgTxt      = "Online Order Confirmation Message. Also include the Tracking Number.";
  private static final String emailSubjectTxt  = "Order Confirmation Subject";
  private static final String emailFromAddress = "bbbbb@gmail.com";

  // Add List of Email address to who email needs to be sent to
  private static final String[] emailList = {"abc@gmail.com", "abcd@gmail.com"};

  public static void main(String args[]) throws Exception
  {
    SendmailUsejavamail smtpMailSender = new SendmailUsejavamail();
    smtpMailSender.postMail( emailList, emailSubjectTxt, emailMsgTxt, emailFromAddress);
    System.out.println("Sucessfully Sent mail to All Users");
  }

  public void postMail( String recipients[ ], String subject,
                            String message , String from) throws MessagingException
  {
    boolean debug = false;

     //Set the host smtp address
     Properties props = new Properties();
     props.put("mail.smtp.host", SMTP_HOST_NAME);
     props.put("mail.smtp.auth", "true");
    Authenticator auth = new SMTPAuthenticator();
    Session session = Session.getDefaultInstance(props, auth);
    session.setDebug(debug);

    // create a message
    Message msg = new MimeMessage(session);

    // set the from and to address
    InternetAddress addressFrom = new InternetAddress(from);
    msg.setFrom(addressFrom);
    InternetAddress[] addressTo = new InternetAddress[recipients.length];
    for (int i = 0; i < recipients.length; i++)
    {
        addressTo[i] = new InternetAddress(recipients[i]);
    }
    msg.setRecipients(Message.RecipientType.TO, addressTo);
    // Setting the Subject and Content Type
    msg.setSubject(subject);
    msg.setContent(message, "text/plain");
    Transport.send(msg);
 }
/**
* SimpleAuthenticator is used to do simple authentication
* when the SMTP server requires it.
*/
private class SMTPAuthenticator extends javax.mail.Authenticator
{

    public PasswordAuthentication getPasswordAuthentication()
    {
        String username = SMTP_AUTH_USER;
        String password = SMTP_AUTH_PWD;
        return new PasswordAuthentication(username, password);
    }
}

}