繁体   English   中英

Java Mail API的传输功能不起作用

[英]java mail API's Transport function not working

我尝试了smtp.gmail.com使用Java API发送邮件,当我使用Transport.send(Mimemessage)时,它显示错误,用户名和密码不被接受。

我已经按照此链接进行了所有操作,但仍然没有用。

然后,我尝试使用SmtpTransport,它可以工作。

我的问题是,为什么Transport.send()不起作用以及SmtpTransport如何工作。

import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class Email {

    Email(String from, String pwd, String to, String sub, String msg) {
        System.out.println("Entered");
        Properties prop = new Properties();
        prop.put("mail.smtp.starttls.enable", "true");
        prop.put("mail.smtp.host", "smtp.gmail.com");
        prop.put("mail.smtp.user", from); // User name
        prop.put("mail.smtp.password", pwd); // password
        prop.put("mail.smtp.port", "587");
        prop.put("mail.smtp.auth", "true");

        Authenticator a = new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("from", "pwd");
            }
        };
        System.out.println("Authenticating");
        Session ses = Session.getDefaultInstance(prop, a);
        System.out.println("Obtained sesion");
        System.out.println(ses);
        try {
            MimeMessage m = new MimeMessage(ses);

            m.setFrom(new InternetAddress(from));
            m.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            m.setSubject(sub);
            m.setText(msg);
            System.out.println("Message constructed");
            Transport.send(m); // / This method causes error
            System.out.println("transported");
            System.out.println("send successfully");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new Email("xxxxxxxxxxxxxxxx@gmail.com", "xxxxxx", "xxxxx@gmail.com",
                "JavaMail", "Firstmail");
    }
}

你必须通过传递犯了一个错误frompwd硬编码到的PasswordAuthentication构造。 只需删除硬编码值,然后将其from pwd传递到方法即可。

我已在您的课堂上作了更正,并给出了下面的代码。

public class Email {


Email(final String from,final String pwd,String to,String sub,String msg){
....

  Authenticator a=new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication()
      {
         return new PasswordAuthentication(from,pwd); 
      }
 };
 ...

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM