Spring發(fā)送郵件如何內(nèi)嵌圖片增加附件
用到的JAR包:
spring.jar mail.jar activation.jar commons-logging.jar log4j-1.2.15.jar
內(nèi)嵌圖片,給定一個CID值即可,增加附件,使用MimeMessageHelper的addAttachment即可
現(xiàn)在一般不會做內(nèi)嵌圖片,因為這樣郵件會很大,容易對服務(wù)器造成壓力,一般做法是使用圖片鏈接
另外,如果要做內(nèi)嵌或發(fā)送圖片,你應(yīng)該使用信用較高的郵箱帳戶,否則會報錯:
554 DT:SPM 發(fā)送的郵件內(nèi)容包含了未被許可的信息,或被系統(tǒng)識別為垃圾郵件。請檢查是否有用戶發(fā)送病毒或者垃圾郵件
對于163郵箱服務(wù)器會產(chǎn)生的其他問題,參見:http://help.163.com/09/1224/17/5RAJ4LMH00753VB8.html
以下是示例代碼:
package test;import java.util.Properties;import javax.mail.Session;import javax.mail.internet.MimeMessage;import org.springframework.core.io.ClassPathResource;import org.springframework.mail.javamail.JavaMailSenderImpl;import org.springframework.mail.javamail.MimeMessageHelper;/** * 這里不做異常處理 */public class SendMail {public static void main(String[] args) throws Exception{// 發(fā)送器JavaMailSenderImpl sender = new JavaMailSenderImpl();sender.setHost('smtp.163.com');sender.setPort(25); // 默認(rèn)就是25sender.setUsername('用戶@163.com'); sender.setPassword('密碼');sender.setDefaultEncoding('UTF-8');// 配置文件對象 Properties props = new Properties(); props.put('mail.smtp.auth', 'true'); // 是否進行驗證Session session = Session.getInstance(props);sender.setSession(session); // 為發(fā)送器指定會話MimeMessage mail = sender.createMimeMessage();MimeMessageHelper helper = new MimeMessageHelper(mail, true);helper.setTo('用戶@163.com'); // 發(fā)送給誰helper.setSubject('強哥邀請,誰敢不從!'); // 標(biāo)題helper.setFrom('用戶@163.com'); // 來自// 郵件內(nèi)容,第二個參數(shù)指定發(fā)送的是HTML格式helper.setText('<font color=’red’>強哥邀請你訪問我的博客:http://cuisuqiang.iteye.com/!</font><br><img src=’cid:myImg’>',true);// 增加CID內(nèi)容ClassPathResource img = new ClassPathResource('abc.jpg');helper.addInline('myImg', img);// 增加附件ClassPathResource file = new ClassPathResource('abc.zip');helper.addAttachment('abc.zip', file);sender.send(mail); // 發(fā)送System.out.println('郵件發(fā)送成功');}}
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. 如何基于python3和Vue實現(xiàn)AES數(shù)據(jù)加密2. ASP.NET MVC前臺動態(tài)添加文本框并在后臺使用FormCollection接收值3. PHP設(shè)計模式(四)原型模式Prototype實例詳解【創(chuàng)建型】4. Python編寫nmap掃描工具5. python 爬取嗶哩嗶哩up主信息和投稿視頻6. Java向Runnable線程傳遞參數(shù)方法實例解析7. 10個提供免費PHP腳本下載的網(wǎng)站8. Java 基于UDP協(xié)議實現(xiàn)消息發(fā)送9. php5.6不能擴展redis.so的解決方法10. PHP擴展之APC——Alternative PHP Cache(可選PHP緩存)
