使用 JSP 发送邮件时出现错误

时间:2020-12-29 13:33:54

标签: java email jsp gmail

我有以下代码使用 JSP 向 gmail 发送电子邮件。我已经添加了库,当我运行它时出现错误,即错误:无法发送邮件.... 代码有什么问题吗?或者我必须添加其他内容,因为我不确定还能做什么

<%@page import="java.util.ArrayList"%>
<%@ page import="java.util.,javax.mail."%>
<%@ page import="javax.mail.internet.*" %>

String result;
final String to = "XXX@gmail.com";
final String subject = "subject";
final String messg = "message";

final String from = "xxx@gmail.com";
final String pass = "xxx";

String host = "smtp.gmail.com";

Properties props = new Properties();

props.put("mail.smtp.host", host);
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.user", from);
props.put("mail.password", pass);
props.put("mail.port", "465");

Session mailSession = Session.getInstance(props, new javax.mail.Authenticator() {
    @Override
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(from, pass);
    }
});

try {
    MimeMessage message = new MimeMessage(mailSession);
    message.setFrom(new InternetAddress(from));
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
    message.setSubject(subject);
    message.setText(messg);
    Transport.send(message);
    result = "mail sent successfully";
} catch (MessagingException mex) {
    mex.printStackTrace();
    result = "Error: unable to send mail....";
}
%>

<title>Sending Mail in JSP</title>
<h2><font color="blue">Sending Mail Using JSP</font></h2>
<b><font color="green"><% out.println(result);%></b>

0 个答案:

没有答案
相关问题