我正在使用
发送电子邮件public void sendEmail(String fromEmailAddr, String toEmailAddr,String subject, String emailBody) {
String host = "xxx";
final String user = "user";
final String password = "password";
// Get system properties
Properties properties = new Properties();
// Setup mail server
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.port", "25");
// Get the default Session object.
Session session = Session.getDefaultInstance(properties, null);
try{
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(fromEmailAddr));
// Set To: header field of the header.
message.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmailAddr));
// Set Subject: header field
message.setSubject(subject);
// Now set the actual message
message.setText(emailBody);
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
当我尝试使用上面的代码发送电子邮件时,它会显示消息Sent message successfully....
,但我没有收到任何电子邮件。另一方面,如果我使用身份验证,那么我收到了电子邮件
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(properties,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user,password);
}
});
为什么?是否有必要为主机提供用户名和密码?我可以通过指定主机,没有提供用户名和密码来发送电子邮件吗?
由于
答案 0 :(得分:0)
我猜端口号可能是个问题。
尝试更改properties.put("mail.smtp.port", "25");
到properties.put("mail.smtp.port", "587");
。
此外,您可以参考this。
答案 1 :(得分:0)
这取决于您正在使用的邮件服务器。
例如,某些邮件服务器允许您在未经身份验证的情况下向同一公司中的任何人发送邮件,但需要进行身份验证才能在公司外部发送邮件。在后一种情况下,如果您在未经过身份验证的情况下发送邮件,则邮件服务器可能会接受该邮件并返回“邮件程序守护程序”失败消息,或者可能只是将邮件丢弃。
另请参阅此common JavaMail mistakes列表。