我正在使用以下代码通过 Java 程序发送电子邮件 (gmail)。我收到AuthenticationFailedException
。我在下面提到了错误。如何解决这个问题?如何在此程序中使用发件人用户名、密码?
package internet;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class mail
{
public static void main(String [] args)
{
String to = "xxx@gmail.com";
String from = "yyy@gmail.com";
String host = "smtp.gmail.com";
Properties properties = System.getProperties();
properties.put("mail.smtp.host", "smtp.gmail.com");
properties.put("mail.smtp.port", "587");
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
Session session = Session.getDefaultInstance(properties);
try{
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
message.setSubject("This is the Subject Line!");
message.setText("This is actual message");
Transport.send(message);
System.out.println("hi");
System.out.println("Sent message successfully....");
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
我收到以下错误
javax.mail.AuthenticationFailedException
at javax.mail.Service.connect(Service.java:267)
at javax.mail.Service.connect(Service.java:137)
at javax.mail.Service.connect(Service.java:86)
at javax.mail.Transport.send0(Transport.java:150)
at javax.mail.Transport.send(Transport.java:80)
at internet.mail.main(mail.java:59)
最佳答案
您必须在t.sendMessage(消息、地址)
之前通过t.connect(主机、用户、密码)
提供您的登录凭据。 (首先使用 Transport t = session.getTransport("smtp")
获取 Transport
对象。
关于java - Java程序中的邮件发送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8986457/