import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class SendEMail
{
public static void main(String [] args)
{
// Recipient's email ID needs to be mentioned.
String to = "*********@gmail.com";
// Sender's email ID needs to be mentioned
String from = "********@gmail.com";
// Assuming you are sending email from localhost
String host = "465";
// Get system properties
Properties properties = System.getProperties();
// Setup mail server
properties.setProperty("mail.smtp.port", host);
properties.put("mail.smtp.user", "*****");
properties.put("mail.smtp.host", "smtp.gmail.com");
properties.put("mail.smtp.port", "587");
properties.put("mail.smtp.starttls.enable","true");
properties.put("mail.smtp.debug", "true");
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.socketFactory.port", "587");
properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
properties.put("mail.smtp.socketFactory.fallback", "false");
properties.setProperty("mail.user", "*******");
properties.setProperty("mail.password", "******");
// Get the default Session object.
Session session = Session.getDefaultInstance(properties);
try{
// 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!");
// Create the message part
BodyPart messageBodyPart = new MimeBodyPart();
// Fill the message
messageBodyPart.setText("This is message body");
// Create a multipar message
Multipart multipart = new MimeMultipart();
// Set text message part
multipart.addBodyPart(messageBodyPart);
// Part two is attachment
messageBodyPart = new MimeBodyPart();
String filename = "file.txt";
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
// Send the complete message parts
message.setContent(multipart );
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
我收到以下错误。 错误:
javax.mail.SendFailedException: Sending failed;
nested exception is:
class javax.mail.AuthenticationFailedException
在浏览同一页面的建议后。我修改了代码,如上所示。但是,这次我收到身份验证错误。请帮我看看这次我哪里错了?
最佳答案
properties.setProperty("mail.smtp.host", host);
这里,主机不是您发送电子邮件的机器。(如代码注释中所写)。 它是您的电子邮件服务器所在的主机。
对于 gmail - 端口 465 上的 smtp.gmail.com
。
您必须根据您的 smtp 服务器进行配置。
关于java - 如何使用JAVA代码发送电子邮件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31431113/