我使用以下程序通过Java发送电子邮件。当我使用这个程序时,我没有收到任何错误。与此同时,我没有发现它,意味着邮件没有被发送。我正在尝试向Gmail发送邮件。这些smtp是否正确?
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "465");
package mail;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.Message.RecipientType;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class mail4 {
private String from;
private String to;
private String subject;
private String text;
public mail4(String from, String to, String subject, String text){
this.from = from;
this.to = to;
this.subject = subject;
this.text = text;
}
public void send(){
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "465");
Session mailSession = Session.getDefaultInstance(props);
Message simpleMessage = new MimeMessage(mailSession);
InternetAddress fromAddress = null;
InternetAddress toAddress = null;
try {
fromAddress = new InternetAddress(from);
toAddress = new InternetAddress(to);
} catch (AddressException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
simpleMessage.setFrom(fromAddress);
simpleMessage.setRecipient(RecipientType.TO, toAddress);
simpleMessage.setSubject(subject);
simpleMessage.setText(text);
Transport.send(simpleMessage);
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
main class
***********
package mail;
public class mail5 {
public static void main(String[] args) {
String from = "xxx@gmail.com";
String to = "yyy@gmail.com";
String subject = "Test";
String message = "A test message";
mail4 sendMail = new mail4(from, to, subject, message);
sendMail.send();
}
}
答案 0 :(得分:0)
尝试添加以下属性:
props.put("mail.smtp.auth", "true");
如果这不起作用,请检查以下链接:
http://www.velocityreviews.com/forums/t141237-send-smtp-mail-using-javamail-with-gmail-account.html
答案 1 :(得分:0)
我认为端口为587
,除非您使用TLS(465
)是正确的。
您没有提供任何身份验证数据:
试试这个:
Session mailSession = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("xxxxxx", "xxxxxx");
}
}
);
答案 2 :(得分:0)
编辑:我误读了代码。您需要使用端口587,因为它是GMail的SMTP端口。您也可以按如下方式编辑yoru道具:
String host = "smtp.gmail.com";
int port = 587;
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");