使用java程序发送电子邮件 [英] Sending Email using java program
本文介绍了使用java程序发送电子邮件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用以下程序通过Java发送电子邮件。当我使用这个程序时,我没有收到任何错误。在那个时候我没有出去,意味着邮件没有被发送。我正尝试将邮件发送到Gmail。这些smtp正确与否?
I am using the following program for sending email through Java. When I use this program, I am not getting any error. At that same time I am not getting out it, means the mail is being not sent. I am trying to send message to Gmail. Are these smtp correct or not?
props.put(mail.smtp.host,smtp.gmail.com); / code>
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();
}
}
推荐答案
I除非你使用TLS(其中 465
)是正确的,否则认为端口是 587
。
您没有提供任何验证数据:
试试这个:
I think the port is 587
unless you're using TLS (for which 465
) is correct.
You're not providing any authentication data:
Try this:
Session mailSession = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("xxxxxx", "xxxxxx");
}
}
);
这篇关于使用java程序发送电子邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文