【问题标题】:Email sent via servlet using JavaMail API not getting through使用 JavaMail API 通过 servlet 发送的电子邮件未通过
【发布时间】:2012-03-22 17:59:15
【问题描述】:

下面是我的代码,它没有给我任何错误,但我的帐户也没有收到电子邮件。我浏览了所有关于这件事的帖子,并相应地修改了我的代码。我对这件事真的很陌生,所以这个问题可能看起来很愚蠢,但仍然欢迎任何方向/建议。 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();
    }
}
 }

【问题讨论】:

  • 你检查过垃圾文件夹吗?
  • 是的,我确实检查了我的垃圾邮件/垃圾文件夹;邮件也不在那里。
  • 哦,是的,一件事是我正在尝试将邮件发送到同一个帐户,因为我正在测试它,但我认为这不会造成任何问题;不过我不确定。
  • 好的,当我四处寻找解决方案时,我发现了 Google 应用程序特定密码。现在我想知道我应该在身份验证时使用我的原始密码还是为我的应用使用谷歌生成的密码?
  • 查看 JavaMail 常见问题以获取调试技巧。此外,1)将 getDefaltInstance 更改为 getInstance,以及 2)您不需要所有套接字工厂的东西(请参阅常见问题解答)。您可能仍然遇到特定于 Gmail 的问题,但常见问题解答将帮助您进行调试。

标签: java email servlets smtp jakarta-mail


【解决方案1】:

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

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

这会让你快速得到答案

【讨论】:

    【解决方案2】:

    您正在使用:

    Properties props = System.getProperties();
    

    改用这个:

    Properties props = new Properties();
    

    如果它不能帮助发布服务器日志,表明电子邮件已经发送。

    【讨论】:

      【解决方案3】:

      这是一种发送邮件应用程序..... 并且它的静态应用程序,它的工作,我们只从这个开发动态应用程序..所以尝试一次.. 添加这个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);
          }
      }
      
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-04-19
        • 2020-10-02
        • 1970-01-01
        • 2017-12-18
        • 1970-01-01
        • 1970-01-01
        • 2015-03-03
        相关资源
        最近更新 更多