我正在尝试从Servlet发送邮件。我有这样的代码,我收到了消息异常。 Stack Over Flow中还有许多其他类似的问题,但它们都没有帮助我。所以我又发了一遍。
string timeInput = Console.ReadLine();
if(timeInput.Length == 4)
{ // if string = four
timeInput = timeInput.Insert(2, ":");
}
string[] timeSplit = timeInput.Split(':');
我的堆栈跟踪就像这样....
@WebServlet(name = "SendMail", urlPatterns = {"/SendMail"})
public class SendMail extends HttpServlet {
final String from = "teamwarrior20@gmail.com";
final String username = "teamwarrior20@gmail.com";
final String password = "iamfromnepal";
String to;
String subject;
String dataMessage;
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
to = req.getParameter("to");
subject = req.getParameter("subject");
dataMessage = req.getParameter("message");
sendMail();
req.getRequestDispatcher("successfullmail.jsp").forward(req, resp);
}
private void sendMail() {
System.out.println(to);
System.out.println(subject);
System.out.println(dataMessage);
Properties props = System.getProperties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props, new javax.mail.Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from, password); //To change body of generated methods, choose Tools | Templates.
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject(subject);
message.setText(dataMessage);
Transport.send(message);
} catch (Exception e) {
e.printStackTrace();
}
}
}
答案 0 :(得分:1)
几个小时后, 我通过添加
解决了这个问题props.put("mail.smtp.user", username);;
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "465");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.debug", "true");
props.put("mail.smtp.auth", "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");
我也开启了不那么安全的应用程序 https://www.google.com/settings/security/lesssecureapps
答案 1 :(得分:0)
更改代码中的两件事
而不是写
Properties props = System.getProperties();
将其更改为
Properties props = new Properties();
同时更改
message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
到
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));
这解决了我的电脑问题。试一试,然后ping我。
答案 2 :(得分:0)
我在gmail的属性中看到了问题。您可以尝试将此行添加到属性中:
props.put("mail.smtp.ssl.trust", "smtp.gmail.com");