无法使用JavaMail api发送邮件
我正在尝试使用以下代码发送邮件:-无法使用JavaMail api发送邮件,java,jakarta-mail,Java,Jakarta Mail,我正在尝试使用以下代码发送邮件:- java.awt.EventQueue.invokeLater( new Runnable() { @Override public void run() { new SwingWorker<Void, Integer>() {
java.awt.EventQueue.invokeLater(
new Runnable() {
@Override
public void run() {
new SwingWorker<Void, Integer>() {
String to = "xx@gmail.com";
// Sender's email ID needs to be mentioned
String from = "xexx@gmail.com";
// Assuming you are sending email from localhost
String host = "localhost";
// Get system properties
// Properties properties = System.getProperties();
// Setup mail server
protected Void doInBackground() throws Exception {
try {
Properties properties = new Properties();
properties.put("mail.smtp.socketFactory.port", "465");
properties.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
properties.put("mail.smtp.starttls.enable", "true");
// Get the default Session object.
Session session = Session.getDefaultInstance(properties);
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the header.
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
// Set Subject: header field
message.setSubject("This is the Subject Line!");
// Now set the actual message
message.setText("Message" + jTextField1.getText() + " xx " + jTextField2.getText());
// Send message
Transport.send(message);
} catch (Exception x) {
x.printStackTrace();
}
return null;
}
protected void process() {
}
protected void done() {
try {
JOptionPane.showMessageDialog(null, "You'll get a response from our team shortly !");
} catch (Exception x) {
}
}
}.execute();
}
如何解决此问题?除非您在本地环境中运行邮件服务器,否则您需要通过其他邮件属性指定一个:
properties.put("mail.smtp.host", aHost);
例如,如果您使用的是Gmail中继,您将:
properties.put("mail.smtp.host", "smtp.gmail.com");
此外,您还需要会话的mail.smtp.auth
属性设置
properties.put("mail.smtp.auth", true);
根据最终使用的主机,您可能还需要提供身份验证信息。例如,同样使用Gmail中继:
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("someUserName", "somePassword");
}
}
);
您的本地计算机是否设置为有效的
SMTP
主机?@c.pramod您是否使用JDK 7?是否完全相同。现在我得到com.sun.mail.smtp.SMTPSendFailedException:需要530-5.5.1身份验证。Exception@c.pramod-您实际上需要提供有效的凭据(我假设您使用的是Gmail中继?)。在示例中所示的位置填写您的帐户用户名和密码。我添加了此行properties.put(“mail.smtp.auth”,“true”);而且成功了。。谢谢回复,顺便说一句!!编辑答案以包含缺少的属性和np。祝项目的其余部分好运。
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("someUserName", "somePassword");
}
}
);