Java發送郵件(帶附件)

實現java發送郵件的過程大體有以下幾步:

  1. 準備一個properties文件,該文件中存放SMTP服務器地址等參數。
  2. 利用properties創建一個Session對象
  3. 利用Session創建Message對象,然后設置郵件主題和正文
  4. 利用Transport對象發送郵件

需要的jar有2個:activation.jar和mail.jar

直接看個demo代碼

#----------------這兩個是構建session必須的字段----------
#smtp服務器
mail.smtp.host=smtp.qq.com
#身份驗證
mail.smtp.auth=true
#--------------------------------------------------------------#發送者的郵箱用戶名
mail.sender.username=xxx@xx.com
#發送者的郵箱密碼
mail.sender.password=xxxxxxxxxxMailServer.properties
View Code

下面是發送郵件的java代碼

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;public class JavaMail {/*** Message對象將存儲我們實際發送的電子郵件信息,* Message對象被作為一個MimeMessage對象來創建并且需要知道應當選擇哪一個JavaMail session。*/private MimeMessage message;/*** Session類代表JavaMail中的一個郵件會話。* 每一個基于JavaMail的應用程序至少有一個Session(可以有任意多的Session)。* * JavaMail需要Properties來創建一個session對象。* 尋找"mail.smtp.host"    屬性值就是發送郵件的主機* 尋找"mail.smtp.auth"    身份驗證,目前免費郵件服務器都需要這一項*/private Session session;/**** 郵件是既可以被發送也可以被受到。JavaMail使用了兩個不同的類來完成這兩個功能:Transport 和 Store。 * Transport 是用來發送信息的,而Store用來收信。對于這的教程我們只需要用到Transport對象。*/private Transport transport;private String mailHost="";private String sender_username="";private String sender_password="";private Properties properties = new Properties();/** 初始化方法*/public JavaMail(boolean debug) {InputStream in = JavaMail.class.getResourceAsStream("MailServer.properties");try {properties.load(in);this.mailHost = properties.getProperty("mail.smtp.host");this.sender_username = properties.getProperty("mail.sender.username");this.sender_password = properties.getProperty("mail.sender.password");} catch (IOException e) {e.printStackTrace();}session = Session.getInstance(properties);session.setDebug(debug);//開啟后有調試信息message = new MimeMessage(session);}/*** 發送郵件* * @param subject*            郵件主題* @param sendHtml*            郵件內容* @param receiveUser*            收件人地址*/public void doSendHtmlEmail(String subject, String sendHtml,String receiveUser) {try {// 發件人//InternetAddress from = new InternetAddress(sender_username);// 下面這個是設置發送人的Nick nameInternetAddress from = new InternetAddress(MimeUtility.encodeWord("幻影")+" <"+sender_username+">");message.setFrom(from);// 收件人InternetAddress to = new InternetAddress(receiveUser);message.setRecipient(Message.RecipientType.TO, to);//還可以有CC、BCC// 郵件主題
            message.setSubject(subject);String content = sendHtml.toString();// 郵件內容,也可以使純文本"text/plain"message.setContent(content, "text/html;charset=UTF-8");// 保存郵件
            message.saveChanges();transport = session.getTransport("smtp");// smtp驗證,就是你用來發郵件的郵箱用戶名密碼
            transport.connect(mailHost, sender_username, sender_password);// 發送
            transport.sendMessage(message, message.getAllRecipients());//System.out.println("send success!");} catch (Exception e) {e.printStackTrace();}finally {if(transport!=null){try {transport.close();} catch (MessagingException e) {e.printStackTrace();}}}}public static void main(String[] args) {JavaMail se = new JavaMail(false);se.doSendHtmlEmail("郵件主題", "郵件內容", "xxx@XX.com");}
}
View Code

上面只能實現文本的發送,如果我們要發送附件,就需要用到Multipart對象了。

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;public class JavaMailWithAttachment {private MimeMessage message;private Session session;private Transport transport;private String mailHost = "";private String sender_username = "";private String sender_password = "";private Properties properties = new Properties();/** 初始化方法*/public JavaMailWithAttachment(boolean debug) {InputStream in = JavaMailWithAttachment.class.getResourceAsStream("MailServer.properties");try {properties.load(in);this.mailHost = properties.getProperty("mail.smtp.host");this.sender_username = properties.getProperty("mail.sender.username");this.sender_password = properties.getProperty("mail.sender.password");} catch (IOException e) {e.printStackTrace();}session = Session.getInstance(properties);session.setDebug(debug);// 開啟后有調試信息message = new MimeMessage(session);}/*** 發送郵件* * @param subject*            郵件主題* @param sendHtml*            郵件內容* @param receiveUser*            收件人地址* @param attachment*            附件*/public void doSendHtmlEmail(String subject, String sendHtml, String receiveUser, File attachment) {try {// 發件人InternetAddress from = new InternetAddress(sender_username);message.setFrom(from);// 收件人InternetAddress to = new InternetAddress(receiveUser);message.setRecipient(Message.RecipientType.TO, to);// 郵件主題
            message.setSubject(subject);// 向multipart對象中添加郵件的各個部分內容,包括文本內容和附件Multipart multipart = new MimeMultipart();// 添加郵件正文BodyPart contentPart = new MimeBodyPart();contentPart.setContent(sendHtml, "text/html;charset=UTF-8");multipart.addBodyPart(contentPart);// 添加附件的內容if (attachment != null) {BodyPart attachmentBodyPart = new MimeBodyPart();DataSource source = new FileDataSource(attachment);attachmentBodyPart.setDataHandler(new DataHandler(source));// 網上流傳的解決文件名亂碼的方法,其實用MimeUtility.encodeWord就可以很方便的搞定// 這里很重要,通過下面的Base64編碼的轉換可以保證你的中文附件標題名在發送時不會變成亂碼//sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();//messageBodyPart.setFileName("=?GBK?B?" + enc.encode(attachment.getName().getBytes()) + "?=");//MimeUtility.encodeWord可以避免文件名亂碼
                attachmentBodyPart.setFileName(MimeUtility.encodeWord(attachment.getName()));multipart.addBodyPart(attachmentBodyPart);}// 將multipart對象放到message中
            message.setContent(multipart);// 保存郵件
            message.saveChanges();transport = session.getTransport("smtp");// smtp驗證,就是你用來發郵件的郵箱用戶名密碼
            transport.connect(mailHost, sender_username, sender_password);// 發送
            transport.sendMessage(message, message.getAllRecipients());System.out.println("send success!");} catch (Exception e) {e.printStackTrace();} finally {if (transport != null) {try {transport.close();} catch (MessagingException e) {e.printStackTrace();}}}}public static void main(String[] args) {JavaMailWithAttachment se = new JavaMailWithAttachment(true);File affix = new File("c:\\測試-test.txt");se.doSendHtmlEmail("郵件主題", "郵件內容", "xxx@XXX.com", affix);//
    }
}帶附件
View Code

來源:https://www.cnblogs.com/yejg1212/archive/2013/06/01/3112702.html

?

轉載于:https://www.cnblogs.com/tiankafei/p/10340643.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/278366.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/278366.shtml
英文地址,請注明出處:http://en.pswp.cn/news/278366.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

google天氣預報接口_將天氣預報添加到谷歌瀏覽器

google天氣預報接口Are you looking for a quick and easy way to see your local weather forecast in Google Chrome? Then you will definitely want to take a good look at the AccuWeather Forecast extension. 您是否正在尋找一種快速簡便的方法來在Google Chrome瀏覽器…

hive中任意相鄰時間段數據獲取

通過sql語句獲取相鄰時段數據不比通過其它編程語言&#xff0c;因為sql里面沒有for循環&#xff0c;故在實現時需要增加一份副表數據&#xff0c;這里對該方法做一個記錄。背景&#xff1a;獲取2017年全年平臺用戶進出貴州省的次數&#xff08;分為進港次數和出港次數&#xff…

strace命令用法

-tt 在每行輸出的前面&#xff0c;顯示毫秒級別的時間 -T 顯示每次系統調用所花費的時間 -v 對于某些相關調用&#xff0c;把完整的環境變量&#xff0c;文件stat結構等打出來。 -f 跟蹤目標進程&#xff0c;以及目標進程創建的所有子進程 -e 控制要跟蹤的事件和跟蹤行為,比如指…

在谷歌瀏覽器中自動翻譯文本

Do you need a quick and simple way to understand an unfamiliar language while browsing the Internet? Then join us as we take a look at the Auto-Translate extension for Google Chrome. 您需要一種快速簡單的方法來瀏覽Internet時理解一種陌生的語言嗎&#xff1f;…

知識點025-服務器的基礎優化腳本

2019獨角獸企業重金招聘Python工程師標準>>> 腳本是借鑒老男孩培訓機構的&#xff0c; 感謝感謝~ mkdir -p /server/scripts cat >> /server/scripts/env.sh <<END #!/bin/bash #author Xiongchao #qq 704816384 #mail 704816384qq.com #selinux off…

PHP實現微信隨機紅包算法和微信紅包的架構設計簡介

微信紅包的架構設計簡介&#xff1a; 原文&#xff1a;https://www.zybuluo.com/yulin718/note/93148 來源于QCon某高可用架構群整理&#xff0c;整理朱玉華。 背景&#xff1a;有某個朋友在朋友圈咨詢微信紅包的架構&#xff0c;于是乎有了下面的文字&#xff08;有誤請提出&a…

微服務實現事務一致性實例

分布式系統架構中&#xff0c;分布式事務問題是一個繞不過去的挑戰。而微服務架構的流行&#xff0c;讓分布式事問題日益突出&#xff01; 下面我們以電商購物支付流程中&#xff0c;在各大參與者系統中可能會遇到分布式事務問題的場景進行詳細的分析&#xff01; 如上圖所示&a…

使用ama0實現串口通信_“ AMA”是什么意思,以及如何使用它?

使用ama0實現串口通信BigTunaOnline/ShutterstockBigTunaOnline / ShutterstockThe term “AMA” is a staple of Reddit, and it has spread to the far corners of the internet. But what does AMA mean, who came up with the word, and how do you use it? “ AMA”一詞是…

火狐 url 亂碼_在Firefox中查看URL作為工具提示

火狐 url 亂碼Would you like a way to view link URLs wherever you mouse is located in a webpage rather than using the Status Bar? Now you can do so very easily with the URL Tooltip extension for Firefox. 您是否想通過一種方式而不是使用狀態欄來查看鏈接URL&am…

Juniper SRX防火墻批量導入set格式配置

Juniper SRX防火墻批量導入set格式配置 SRX在進行大量配置時可能會出現一些小問題&#xff0c;可以使用load set terminal命令導入大量set格式的配置。 root# load set terminal[Type ^D at a new line to end input] 輸入配置set applications application tcp-1521 protocol …

java虛擬機之內存分配

Java 的自動內存管理主要是針對對象內存的回收和對象內存的分配。同時&#xff0c;Java 自動內存管理最核心的功能是 堆 內存中對象的分配與回收。 JDK1.8之前的堆內存示意圖&#xff1a; 從上圖可以看出堆內存分為新生代、老年代和永久代。新生代又被進一步分為&#xff1a;Ed…

知道無人駕駛的網絡安全有多重要嗎?英國政府都決定插手開發了

這樣的策略也被解讀為&#xff0c;英國政府希望借此搶占未來無人駕駛汽車研發的先機。 相信看過下午我們有關速8中黑科技的文章的朋友們&#xff0c;一定對有關車輛網絡安全印象深刻&#xff0c;也足以見得未來無人駕駛時代的網絡安全問題有多重要。所以&#xff0c;英國政府決…

linux uniq命令_如何在Linux上使用uniq命令

linux uniq命令Fatmawati Achmad Zaenuri/ShutterstockFatmawati Achmad Zaenuri / ShutterstockThe Linux uniq command whips through your text files looking for unique or duplicate lines. In this guide, we cover its versatility and features, as well as how you c…

解決 display 和 transition 沖突的問題

問題&#xff1a; 既需要“顯示、隱藏”’效果&#xff0c;也需要動畫效果。此時使用了xxx.style.display "none / block" 之后&#xff0c;我們發現 transition 動畫效果就沒有了。 解決辦法一&#xff1a;用定時器&#xff08;這種方法并不好&#xff09; btn2.on…

win10任務欄和開始菜單_如何將網站固定到Windows 10任務欄或開始菜單

win10任務欄和開始菜單Having quick access to frequently-used or hard to remember websites can save you time and frustration. Whether you use Chrome, Firefox, or Edge, you can add a shortcut to any site right to your Windows 10 taskbar or Start menu. 快速訪問…

智能家居的尷尬:概念比用戶火

智能家居概念的走俏與用戶的接受程度成鮮明的對比&#xff0c;如何才能撬開這個市場&#xff0c;這是整個行業都需要思考的問題。 追溯起源&#xff0c;智能家居已經有20年的歷史&#xff0c;但由于技術缺陷、價格昂貴&#xff0c;實用性差、安裝復雜及產品同質化嚴重等原因&a…

WEB_矛盾

題目鏈接&#xff1a;http://123.206.87.240:8002/get/index1.php 題解&#xff1a; 打開題目&#xff0c;看題目信息&#xff0c;本題首先要弄清楚 is_numeric() 函數的作用 作用如下圖&#xff1a; 即想要輸出flag&#xff0c;num既不能是數字字符&#xff0c;不能為數1&…

如何在Windows上解決藍牙問題

Bluetooth gives you the freedom to move without a tether, but it isn’t always the most reliable way to use wireless devices. If you’re having trouble with Bluetooth on your Windows machine, you can follow the steps below to troubleshoot it. 藍牙使您可以不…

Multicast注冊中心

1234提供方啟動時廣播自己的地址。   消費方啟動時廣播訂閱請求。   提供方收到訂閱請求時&#xff0c;單播自己的地址給訂閱者&#xff0c;如果設置了unicastfalse&#xff0c;則廣播給訂閱者。   消費方收到提供方地址時&#xff0c;連接該地址進行RPC調用。 <du…

阻止a鏈接跳轉方法總結

總結下a標簽阻止默認行為的幾種簡單方法(1) <a href"javascript:void(0);" > 點我 </a> onclick方法負責執行js函數&#xff0c;而void是一個操作符&#xff0c;void(0)返回undefined&#xff0c;地址不發生跳轉。 <a href"javascript:;&qu…