Java發送郵件的方法

來源:互聯網
上載者:User

標籤:encode   factory   rda   setfile   set   text   inter   發送郵件   users   

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發送郵件的方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.