我不熟悉这个函数在java中发送邮件。我在发送电子邮件以确认用户注册后收到错误。
以下是 TextMail:
中的代码public class TextMail extends HttpServlet {
static String sender_email = "abc@gmail.com";
static String password = "aaaa1111";
static String host = "smtp.gmail.com";
static String port = "465";
private static class MailAuthenticator extends javax.mail.Authenticator {
@Override
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(sender_email, password);
}
}
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try {
System.out.println("inside textmail");
System.out.println(request.getParameter("to"));
System.out.println(request.getParameter("text"));
System.out.println(request.getParameter("subject"));
String to = request.getParameter("to");
String text = request.getParameter("text");
String subject = request.getParameter("subject");
Properties props = new Properties();
props.put("mail.smtp.user", sender_email);
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", port);
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.socketFactory.port", port);
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
Authenticator auth = new MailAuthenticator();
Session session = Session.getInstance(props, auth);
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(sender_email));
message.setSubject(subject);
message.setText(text);
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
Transport.send(message);
System.out.println("execute textmail");
} catch (Exception mex) {
throw new ServletException(mex);
}
}
以上代码的参数是从另一个服务器发送的:
response.sendRedirect("TextMail?to="+ul.getEmail()+"&text=path?UID="+u.getIduser()+"&subject=Comfirmation");
并且这些参数成功传递给TextMail
答案 0 :(得分:3)
您正在混合使用TLS和SSL配置,但这不正确。您需要选择要使用的那个。特别是,如果您想使用SSL,您应该使用以下内容:
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");
或者如果您想使用TLS,您可以使用以下内容:
Properties props = new Properties();
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");
另请注意,您无法使用经典gmail凭据通过客户端发送电子邮件,但您应为此设置特定于应用程序的密码(有关更多信息,请参阅https://support.google.com/accounts/answer/185833)
有关配置通用邮件客户端以使用Gmail的详细信息,请查看https://support.google.com/mail/answer/13287
经过上述考虑后,您可以在http://www.mkyong.com/java/javamail-api-sending-email-via-gmail-smtp-example
看到两个正在运行的java示例