1

我正在使用发送电子邮件

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);
                }
        });

为什么 ?是否需要为主机提供用户名和密码?我可以通过仅指定主机而不提供用户名和密码来发送电子邮件吗?

谢谢

4

2 回答 2

0

I guess the port number might be the issue.

Try changing properties.put("mail.smtp.port", "25");

to properties.put("mail.smtp.port", "587");.

Further you can refer this.

于 2013-07-25T12:32:05.680 回答
0

这取决于您使用的邮件服务器。

例如,某些邮件服务器允许您无需身份验证即可向同一公司内的任何人发送邮件,但在公司外部发送邮件则需要进行身份验证。在后一种情况下,如果您在没有验证的情况下发送邮件,邮件服务器可能会接受该消息并返回“mailer-daemon”失败消息,或者可能只是将消息丢弃。

此外,请参阅此常见 JavaMail 错误列表。

于 2013-07-25T23:40:46.390 回答