我想做什么:使用以下代码向smtp.live.com主机发送基本电子邮件,以便通过电子邮件发送给使用Java程序的人:
import java.util.*;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import com.sun.mail.smtp.SMTPTransport;
public class emailTest {
public static void main(String[] args) {
String to = "example@live.com";
String from = "example@live.com";
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.host", "smtp.live.com");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
Session session = Session.getDefaultInstance(props);
session.setDebug(true);
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject("Java");
message.setText("Java");
Transport trans = session.getTransport("smtp");
trans.connect("smtp.live.com", 587, "example@live.com", "password");
Transport.send(message);
System.out.println("Message Sent!");
} catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
问题:当我尝试发送电子邮件时,我收到此错误。
javax.mail.AuthenticationFailedException: failed to connect
at javax.mail.Service.connect(Service.java:322)
at javax.mail.Service.connect(Service.java:172)
at javax.mail.Service.connect(Service.java:121)
at javax.mail.Transport.send0(Transport.java:190)
at javax.mail.Transport.send(Transport.java:120)
at emailTest.main(emailTest.java:39)
我的问题:我只是想知道自己做错了什么,因为我花了几个小时试图找到解决这个问题的不同方法。
答案 0 :(得分:0)
好的,我很快就弄清楚我做错了什么。我无法使用Transport.send(消息)发送消息。
需要进行更改:相反,我必须使用trans.sendMessage(message,message.getAllRecipients())。
这里是固定代码:
import java.util.*;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import com.sun.mail.smtp.SMTPTransport;
public class emailTest {
public static void main(String[] args) {
String to = "example@live.com";
String from = "example@live.com";
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.host", "smtp.live.com");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
Session session = Session.getDefaultInstance(props);
session.setDebug(true);
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject("Java");
message.setText("Java");
Transport trans = session.getTransport("smtp");
trans.connect("smtp.live.com", 587, "example@live.com", "password");
trans.sendMessage(message, message.getAllRecipients());
System.out.println("Message Sent!");
} catch (MessagingException mex) {
mex.printStackTrace();
}
}
}