Java發送郵件的方法
1.需要的jar包
2.具體實現方法
1.設置郵箱主機、需要認證、郵箱協議
Properties pro=new Properties();
pro.setProperty("mail.host", "smtp.qq.com");
pro.setProperty("mail.smtp.auth", "true");
pro.setProperty("mail.transport.protocol", "smtp");
2.設置校驗器
Authenticator auth=new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("[email protected]","qzeagwfnyxvgjgff");
}
};
3.設置套接層,是為了保證協議以及運輸的安全可靠性
MailSSLSocketFactory sf=new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
pro.put("mail.smtp.ssl.enable", "true");
pro.put("mail.smto.ssl.SocketFactory", sf);
4.創建一封新郵件
//創建session
Session session=Session.getInstance(pro,auth);
session.setDebug(true);
//創建一份郵件
MimeMessage mime=new MimeMessage(session);
//填寫發送人
mime.setFrom(new InternetAddress("[email protected]"));
//填寫接收人
mime.setRecipients(RecipientType.TO,"[email protected]");
//設置主題
mime.setSubject("hello");
//設置正文
mime.setContent("hello,你好!","text/html;charset=utf-8");
Transport.send(mime);
System.out.println("發送成功");
Java發送帶附件郵件的方法
只需要在設置正文那裏註釋掉,然後改成:
//發送帶附件的郵件
MimeMultipart list =new MimeMultipart();
//創建body主體放置內容
MimeBodyPart b1=new MimeBodyPart();
b1.attachFile(new File("C:\\Users\\Administrator\\Desktop\\7.jpg"));
//中文轉碼
b1.setFileName(MimeUtility.encodeText("蠟筆小新耍流氓.jpg"));
list.addBodyPart(b1);
MimeBodyPart b2=new MimeBodyPart();
b2.setContent("hello,你好!","text/html;charset=utf-8");
list.addBodyPart(b2);
mime.setContent(list);
Transport.send(mime);
System.out.println("發送成功");
Java發送郵件的方法