使用java mail-api发送电子邮件失败

时间:2015-08-28 09:47:38

标签: java javamail

绝望地尝试向自己发送电子邮件:

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

Properties props = new Properties();
    props.put("mail.smtp.host", "smtp.web.de");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");

    Session session = Session.getInstance(props);

    Message msg = new MimeMessage(session);
    try {
        msg.setFrom(new InternetAddress("myveryownemail@web.de"));
        msg.setRecipients(Message.RecipientType.TO, new InternetAddress[]{new InternetAddress("myveryownemail@web.de")});
        msg.setSubject("whatever");
        msg.setContent("whatever", "text/plain");

        Transport transport = session.getTransport("smtp");
        transport.connect("smtp.web.de", 587, "myveryownemail", "myveryownandcorrectpassword");

        Transport.send(msg);
    } catch (MessagingException e) {
        e.printStackTrace();
    }

我得到了 javax.mail.AuthenticationFailedException:连接失败,未指定密码?
但用户名和密码是绝对正确的(尝试使用和不使用@ web.de的用户名)。密码是我用于正常登录我的邮件帐户的密码。 don't不明白

5 个答案:

答案 0 :(得分:3)

  

使用您的用户名和密码创建 javax.mail.Session 对象,如下所示   密码: -

 Session session = Session.getInstance(props,
          new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
          });

参考教程: - http://www.mkyong.com/java/javamail-api-sending-email-via-gmail-smtp-example/

答案 1 :(得分:1)

使用smtp用户和密码设置以下属性

if (array_search($id,$a)) {
   echo "Found";
} else {
   echo "Not Found"
}

参考:http://www.tutorialspoint.com/java/java_sending_email.htm

答案 2 :(得分:1)

过去我解决了类似的问题,加上这个:

if ("true".equals(emailConfig.get("mail.smtp.auth"))) {
    session = Session.getInstance(properties, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(emailConfig.get("mail.smtp.user"), emailConfig.get("mail.smtp.password"));
        }
    });
}

Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(emailFromAddress));
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(emailToAdrress));
msg.setSubject(mailSubject);
msg.setText(mailMessageBody);
Transport.send(msg);

会话 javax.mail.Session

答案 3 :(得分:0)

希望您在项目中包含“mail.jar”和“activation.jar”。这link可以帮助您

答案 4 :(得分:0)

您正在调用Transport.send静态方法,该方法忽略您创建和连接的传输实例。改为调用sendMessage方法,或者跳过创建自己的Transport实例并调用带有用户名和密码的静态send方法。

这是JavaMail common mistakes之一。