【发布时间】:2022-01-14 12:23:12
【问题描述】:
我正在尝试通过 Gmail 发送电子邮件,但出现异常“未知的 SMTP 主机:smtp.gmail.com”。 我已经开启不太安全的应用访问,两步验证应该关闭。
public class MonitoringMail
{
public void sendMail(String mailServer, String from, String[] to, String subject, String messageBody) throws MessagingException, AddressException
{
boolean debug = false;
Properties props = new Properties();
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.EnableSSL.enable","true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", mailServer);
props.put("mail.debug", "true");
props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.port", "465");
props.setProperty("mail.smtp.socketFactory.port", "465");
Authenticator auth = new SMTPAuthenticator();
Session session = Session.getDefaultInstance(props, auth);
session.setDebug(debug);
try
{
Transport bus = session.getTransport("smtp");
bus.connect();
Message message = new MimeMessage(session);
//X-Priority values are generally numbers like 1 (for highest priority), 3 (normal) and 5 (lowest).
message.addHeader("X-Priority", "1");
message.setFrom(new InternetAddress(from));
InternetAddress[] addressTo = new InternetAddress[to.length];
for (int i = 0; i < to.length; i++)
addressTo[i] = new InternetAddress(to[i]);
message.setRecipients(Message.RecipientType .TO, addressTo);
message.setSubject(subject);
BodyPart body = new MimeBodyPart();
// body.setText(messageBody);
body.setContent(messageBody,"text/html");
MimeMultipart multipart = new MimeMultipart();
multipart.addBodyPart(body);
// multipart.addBodyPart(attachment);
message.setContent(multipart);
Transport.send(message);
System.out.println("Sucessfully Sent mail to All Users");
bus.close();
}
catch (MessagingException mex)
{
mex.printStackTrace();
}
}
它早些时候工作,但一周后我得到了一个例外。 我尝试解决此异常,我花了 3 天时间,但我无法解决这些问题,请尝试解决此问题。
【问题讨论】: