我在使用 javax.mail.jar 发送邮件时遇到(无法连接到 SMTP 主机)错误。我可以通过 smtp.gmail.com 发送邮件,但是当我尝试连接到我公司的邮件服务器时,我收到了错误消息。我尝试从 telnet 发送邮件,并且另一个 python 程序也在运行,它使用相同的邮件服务器(ip 和端口)发送邮件,我们的 bugzilla 服务器也在相同的 ip 和端口上运行,它是成功的发送邮件。我尝试通过 SMTP 附加程序从 java 以及 log4j 配置相同但没有成功。
请指导我。
提前致谢
我的代码如下 -
private Session getSession()
{
Authenticator authenticator = new Authenticator();
Properties properties = new Properties();
properties.setProperty("mail.smtp.submitter", authenticator
.getPasswordAuthentication().getUserName());
properties.setProperty("mail.smtp.auth", "true");
properties.put("mail.smtp.socketFactory.port", "25");
//properties.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
properties.setProperty("mail.smtp.starttls.enable", "true");
properties.setProperty("mail.smtp.host", smtpServer);
properties.setProperty("mail.smtp.port", smtpPort);
return Session.getInstance(properties, authenticator);
}
private class Authenticator extends javax.mail.Authenticator
{
private final javax.mail.PasswordAuthentication authentication;
public Authenticator()
{
authentication =
new javax.mail.PasswordAuthentication(username, password);
}
@Override
protected javax.mail.PasswordAuthentication getPasswordAuthentication()
{
return authentication;
}
}
public boolean sendEmail() throws MessagingException
{
boolean isSuccess = false;
String setBody = "";
String setSubject = "";
try
{
Message message = new MimeMessage(getSession());
setReceipients(message);
message.addFrom(new InternetAddress[]
{ new InternetAddress(emailFrom, "Notification") });
setSubject = emailSubject;
message.setSubject(setSubject);
setBody = emailBody + "\nThis is a System Generated Mail";
message.setContent(setBody, "text/plain");
Transport.send(message);
log.info("Mail Sent Successfully to - " + emailTo);
isSuccess = true;
}
catch (UnsupportedEncodingException ex)
{
log.error("Error in sending Mail without Attachment- "
+ ex.getMessage());
log.warn("Mail Sending Failed for Mail ID:" + emailTo);
}
catch (SendFailedException e)
{
log.error("Invalid Addresses \"" + emailTo + "\" specified:"
+ e.getMessage());
log.warn("Mail Sending Failed for Mail ID:" + emailTo);
}
catch (Exception e)
{
log.error("Error in sending Mail without Attachment- "
+ e.getMessage());
log.warn("Mail Sending Failed for Mail ID:" + emailTo);
}
return isSuccess;
}