【发布时间】: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