郵箱開啟SMTP

image.png
導包
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1.1</version>
</dependency>
public class SendMail {
public static void main(String [] args)
{
// 收件人電子郵箱
String to = "xx@qq.com";
// 發(fā)件人電子郵箱
String from = "xx@qq.com";
// 指定發(fā)送郵件的主機為 localhost
String host = "smtp.qq.com"; //QQ 郵件服務(wù)器
// 獲取系統(tǒng)屬性
Properties properties = System.getProperties();
// 設(shè)置郵件服務(wù)器
properties.setProperty("mail.smtp.host", host);
properties.put("mail.smtp.auth", "true");
// 獲取默認session對象
Session session = Session.getDefaultInstance(properties,new Authenticator(){
public PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication("xxx@qq.com", ""); //發(fā)件人郵件用戶名,密碼是郵箱的授權(quán)碼,不是登錄密碼
}
});
try{
// 創(chuàng)建默認的 MimeMessage 對象。
MimeMessage message = new MimeMessage(session);
// Set From: 頭部頭字段
message.setFrom(new InternetAddress(from));
// Set To: 頭部頭字段
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
// Set Subject: 頭字段
message.setSubject("This is the Subject Line!");
// 創(chuàng)建消息部分
BodyPart messageBodyPart = new MimeBodyPart();
// 消息
messageBodyPart.setText("This is message body");
// 創(chuàng)建多重消息
Multipart multipart = new MimeMultipart();
// 設(shè)置文本消息部分
multipart.addBodyPart(messageBodyPart);
// 附件部分
messageBodyPart = new MimeBodyPart();
String filename = "wanted.png";
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
// 發(fā)送完整消息
message.setContent(multipart );
// 發(fā)送消息
Transport.send(message);
System.out.println("Sent message successfully....");
}catch (Exception mex) {
mex.printStackTrace();
}
}
}