① java里如何判斷Email是否發送成功
package com.liuns.mail.test;
import java.util.Date;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
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 MailTest {
//發送的郵箱 內部代碼只適用qq郵箱
private static final String USER = "[email protected]";
//授權密碼 通過QQ郵箱設置->賬戶->POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服務->開啟POP3/SMTP服務獲取
private static final String PWD = "xxx";
private String[] to;
private String[] cc;//抄送
private String[] bcc;//密送
private String[] fileList;//附件
private String subject;//主題
private String content;//內容,可以用html語言寫
public void sendMessage() throws Exception {
// 配置發送郵件的環境屬性
final Properties props = new Properties();
//下面兩段代碼是設置ssl和埠,不設置發送不出去。
props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
//props.setProperty("mail.smtp.port", "465");
props.setProperty("mail.smtp.socketFactory.port", "465");
// 表示SMTP發送郵件,需要進行身份驗證
props.setProperty("mail.transport.protocol", "smtp");// 設置傳輸協議
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", "smtp.qq.com");//QQ郵箱的伺服器 如果是企業郵箱或者其他郵箱得更換該伺服器地址
// 發件人的賬號
props.put("mail.user", USER);
// 訪問SMTP服務時需要提供的密碼
props.put("mail.password", PWD);
// 構建授權信息,用於進行SMTP進行身份驗證
Authenticator authenticator = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
// 用戶名、密碼
String userName = props.getProperty("mail.user");
String password = props.getProperty("mail.password");
return new PasswordAuthentication(userName, password);
}
};
// 使用環境屬性和授權信息,創建郵件會話
Session mailSession = Session.getInstance(props, authenticator);
// 創建郵件消息
MimeMessage message = new MimeMessage(mailSession);
BodyPart messageBodyPart = new MimeBodyPart();
Multipart multipart = new MimeMultipart();
// 設置發件人
InternetAddress form = new InternetAddress(
props.getProperty("mail.user"));
message.setFrom(form);
//發送
if (to != null) {
String toList = getMailList(to);
InternetAddress[] iaToList = new InternetAddress().parse(toList);
message.setRecipients(RecipientType.TO, iaToList); // 收件人
}
//抄送
if (cc != null) {
String toListcc = getMailList(cc);
InternetAddress[] iaToListcc = new InternetAddress().parse(toListcc);
message.setRecipients(RecipientType.CC, iaToListcc); // 抄送人
}
//密送
if (bcc != null) {
String toListbcc = getMailList(bcc);
InternetAddress[] iaToListbcc = new InternetAddress().parse(toListbcc);
message.setRecipients(RecipientType.BCC, iaToListbcc); // 密送人
}
message.setSentDate(new Date()); // 發送日期 該日期可以隨意寫,你可以寫上昨天的日期(效果很特別,親測,有興趣可以試試),或者抽象出來形成一個參數。
message.setSubject(subject); // 主題
message.setText(content); // 內容
//顯示以html格式的文本內容
messageBodyPart.setContent(content,"text/html;charset=utf-8");
multipart.addBodyPart(messageBodyPart);
//保存多個附件
if(fileList!=null){
addTach(fileList, multipart);
}
message.setContent(multipart);
// 發送郵件
Transport.send(message);
}
public void setTo(String[] to) {
this.to = to;
}
public void setCc(String[] cc) {
this.cc = cc;
}
public void setBcc(String[] bcc) {
this.bcc = bcc;
}
public void setSubject(String subject) {
this.subject = subject;
}
public void setContent(String content) {
this.content = content;
}
public void setFileList(String[] fileList) {
this.fileList = fileList;
}
private String getMailList(String[] mailArray) {
StringBuffer toList = new StringBuffer();
int length = mailArray.length;
if (mailArray != null && length < 2) {
toList.append(mailArray[0]);
} else {
for (int i = 0; i < length; i++) {
toList.append(mailArray[i]);
if (i != (length - 1)) {
toList.append(",");
}
}
}
return toList.toString();
}
//添加多個附件
public void addTach(String fileList[], Multipart multipart) throws Exception {
for (int index = 0; index < fileList.length; index++) {
MimeBodyPart mailArchieve = new MimeBodyPart();
FileDataSource fds = new FileDataSource(fileList[index]);
mailArchieve.setDataHandler(new DataHandler(fds));
mailArchieve.setFileName(MimeUtility.encodeText(fds.getName(),"UTF-8","B"));
multipart.addBodyPart(mailArchieve);
}
}
//以下是演示demo
public static void main(String args[]) {
MailTest mail = new MailTest();
mail.setSubject("java郵件");
mail.setContent("你好 這是第一個java 程序發送郵件");
//收件人 可以發給其他郵箱(163等) 下同
mail.setTo(new String[] {"[email protected]"});
//抄送
// mail.setCc(new String[] {"[email protected]","[email protected]"});
//密送
//mail.setBcc(new String[] {"[email protected]","[email protected]"});
//發送附件列表 可以寫絕對路徑 也可以寫相對路徑(起點是項目根目錄)
// mail.setFileList(new String[] {"D:\\aa.txt"});
//發送郵件
try {
mail.sendMessage();
System.out.println("發送郵件成功!");
} catch (Exception e) {
System.out.println("發送郵件失敗!");
e.printStackTrace();
}
}
}
② 怎麼用JAVA實現郵件發送
一個小例子,也可使用其他api
importjava.util.Properties;
importjavax.mail.Address;
importjavax.mail.Authenticator;
importjavax.mail.BodyPart;
importjavax.mail.Message;
importjavax.mail.Multipart;
importjavax.mail.PasswordAuthentication;
importjavax.mail.Session;
importjavax.mail.Transport;
importjavax.mail.internet.InternetAddress;
importjavax.mail.internet.MimeBodyPart;
importjavax.mail.internet.MimeMessage;
importjavax.mail.internet.MimeMultipart;
importjavax.mail.internet.MimeUtility;
publicclassTest{
//test
publicstaticvoidmain(String[]args)throwsException{
sendEmail("smtp.163.com","測試","測試","!!!收件人地址!!!","!!!發件人郵箱用戶名!!!","!!!郵箱密碼!!!","發件人昵稱");
}
/**
*
*@paramsmtp
*@throwsException
*/
publicstaticvoidsendEmail(StringemailServer,Stringsubject,StringmailBody,Stringreceiver,finalStringusername,finalStringpassword,Stringnickname)throwsException{
Propertiesprops=newProperties();
props.put("mail.smtp.auth","true");
props.setProperty("mail.transport.protocol","smtp");
props.setProperty("mail.smtp.host",emailServer);
props.setProperty("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.smtp.socketFactory.fallback","false");
props.setProperty("mail.smtp.port","465");
props.setProperty("mail.smtp.socketFactory.port","465");
Sessionsession=Session.getDefaultInstance(props,newAuthenticator(){
(){
(username,password);
}
});
session.setDebug(true);
MimeMessagemimeMsg=newMimeMessage(session);
Multipartmp=newMimeMultipart();
mimeMsg.setSubject(MimeUtility.encodeText(subject,"utf-8",null));
nickname=MimeUtility.encodeText(nickname,"utf-8",null);
mimeMsg.setFrom(newInternetAddress(username,nickname,"UTF-8"));
BodyPartbp=newMimeBodyPart();
bp.setContent(mailBody,"text/html;charset=utf-8");
mp.addBodyPart(bp);
mimeMsg.setRecipients(Message.RecipientType.TO,InternetAddress.parse(receiver));
mimeMsg.setContent(mp);
mimeMsg.saveChanges();
Transporttransport=session.getTransport();
transport.connect(username,password);
Address[]allRecipients=mimeMsg.getAllRecipients();
transport.sendMessage(mimeMsg,allRecipients);
transport.close();
}
}
③ 如何寫一個JAVA類可以實現郵件發送功能,也可以實現群發功能
package byd.core;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import sun.misc.BASE64Encoder;
/**
* 該類使用Socket連接到郵件伺服器, 並實現了向指定郵箱發送郵件及附件的功能。
*
* @author Kou Hongtao
*/
public class Email {
/**
* 換行符
*/
private static final String LINE_END = "\r\n";
/**
* 值為「true」輸出高度信息(包括伺服器響應信息),值為「 false」則不輸出調試信息。
*/
private boolean isDebug = true;
/**
* 值為「true」則在發送郵件{@link Mail#send()} 過程中會讀取伺服器端返回的消息,
* 並在郵件發送完畢後將這些消息返回給用戶。
*/
private boolean isAllowReadSocketInfo = true;
/**
* 郵件伺服器地址
*/
private String host;
/**
* 發件人郵箱地址
*/
private String from;
/**
* 收件人郵箱地址
*/
private List<String> to;
/**
* 抄送地址
*/
private List<String> cc;
/**
* 暗送地址
*/
private List<String> bcc;
/**
* 郵件主題
*/
private String subject;
/**
* 用戶名
*/
private String user;
/**
* 密碼
*/
private String password;
/**
* MIME郵件類型
*/
private String contentType;
/**
* 用來綁定多個郵件單元{@link #partSet}
* 的分隔標識,我們可以將郵件的正文及每一個附件都看作是一個郵件單元 。
*/
private String boundary;
/**
* 郵件單元分隔標識符,該屬性將用來在郵件中作為分割各個郵件單元的標識 。
*/
private String boundaryNextPart;
/**
* 傳輸郵件所採用的編碼
*/
private String contentTransferEncoding;
/**
* 設置郵件正文所用的字元集
*/
private String charset;
/**
* 內容描述
*/
private String contentDisposition;
/**
* 郵件正文
*/
private String content;
/**
* 發送郵件日期的顯示格式
*/
private String simpleDatePattern;
/**
* 附件的默認MIME類型
*/
private String defaultAttachmentContentType;
/**
* 郵件單元的集合,用來存放正文單元和所有的附件單元。
*/
private List<MailPart> partSet;
private List<MailPart> alternativeList;
private String mixedBoundary;
private String mixedBoundaryNextPart;
/**
* 不同類型文件對應的{@link MIME} 類型映射。在添加附件
* {@link #addAttachment(String)} 時,程序會在這個映射中查找對應文件的
* {@link MIME} 類型,如果沒有, 則使用
* {@link #defaultAttachmentContentType} 所定義的類型。
*/
private static Map<String, String> contentTypeMap;
private static enum TextType {
PLAIN("plain"), HTML("html");
private String v;
private TextType(String v) {
this.v = v;
}
public String getValue() {
return this.v;
}
}
static {
// MIME Media Types
contentTypeMap = new HashMap<String, String>();
contentTypeMap.put("xls", "application/vnd.ms-excel");
contentTypeMap.put("xlsx", "application/vnd.ms-excel");
contentTypeMap.put("xlsm", "application/vnd.ms-excel");
contentTypeMap.put("xlsb", "application/vnd.ms-excel");
contentTypeMap.put("doc", "application/msword");
contentTypeMap.put("dot", "application/msword");
contentTypeMap.put("docx", "application/msword");
contentTypeMap.put("docm", "application/msword");
contentTypeMap.put("dotm", "application/msword");
}
/**
* 該類用來實例化一個正文單元或附件單元對象,他繼承了 {@link Mail}
* ,在這里製作這個子類主要是為了區別郵件單元對象和郵件服務對象 ,使程序易讀一些。
* 這些郵件單元全部會放到partSet 中,在發送郵件 {@link #send()}時, 程序會調用
* {@link #getAllParts()} 方法將所有的單元合並成一個符合MIME格式的字元串。
*
* @author Kou Hongtao
*/
private class MailPart extends Email {
public MailPart() {
}
}
/**
* 默認構造函數
*/
public Email() {
defaultAttachmentContentType = "application/octet-stream";
simpleDatePattern = "yyyy-MM-dd HH:mm:ss";
boundary = "--=_NextPart_zlz_3907_" + System.currentTimeMillis();
boundaryNextPart = "--" + boundary;
contentTransferEncoding = "base64";
contentType = "multipart/mixed";
charset = Charset.defaultCharset().name();
partSet = new ArrayList<MailPart>();
alternativeList = new ArrayList<MailPart>();
to = new ArrayList<String>();
cc = new ArrayList<String>();
bcc = new ArrayList<String>();
mixedBoundary = "=NextAttachment_zlz_" + System.currentTimeMillis();
mixedBoundaryNextPart = "--" + mixedBoundary;
}
/**
* 根據指定的完整文件名在 {@link #contentTypeMap} 中查找其相應的MIME類型,
* 如果沒找到,則返回 {@link #defaultAttachmentContentType}
* 所指定的默認類型。
*
* @param fileName
* 文件名
* @return 返迴文件對應的MIME類型。
*/
private String getPartContentType(String fileName) {
String ret = null;
if (null != fileName) {
int flag = fileName.lastIndexOf(".");
if (0 <= flag && flag < fileName.length() - 1) {
fileName = fileName.substring(flag + 1);
}
ret = contentTypeMap.get(fileName);
}
if (null == ret) {
ret = defaultAttachmentContentType;
}
return ret;
}
/**
* 將給定字元串轉換為base64編碼的字元串
*
* @param str
* 需要轉碼的字元串
* @param charset
* 原字元串的編碼格式
* @return base64編碼格式的字元
*/
private String toBase64(String str, String charset) {
if (null != str) {
try {
return toBase64(str.getBytes(charset));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return "";
}
/**
* 將指定的位元組數組轉換為base64格式的字元串
*
* @param bs
* 需要轉碼的位元組數組
* @return base64編碼格式的字元
*/
private String toBase64(byte[] bs) {
return new BASE64Encoder().encode(bs);
}
/**
* 將給定字元串轉換為base64編碼的字元串
*
* @param str
* 需要轉碼的字元串
* @return base64編碼格式的字元
*/
private String toBase64(String str) {
return toBase64(str, Charset.defaultCharset().name());
}
/**
* 將所有的郵件單元按照標準的MIME格式要求合並。
*
* @return 返回一個所有單元合並後的字元串。
*/
private String getAllParts() {
StringBuilder sbd = new StringBuilder(LINE_END);
sbd.append(mixedBoundaryNextPart);
sbd.append(LINE_END);
sbd.append("Content-Type: ");
sbd.append("multipart/alternative");
sbd.append(";");
sbd.append("boundary=\"");
sbd.append(boundary).append("\""); // 郵件類型設置
sbd.append(LINE_END);
sbd.append(LINE_END);
sbd.append(LINE_END);
addPartsToString(alternativeList, sbd, getBoundaryNextPart());
sbd.append(getBoundaryNextPart()).append("--");
sbd.append(LINE_END);
addPartsToString(partSet, sbd, mixedBoundaryNextPart);
sbd.append(LINE_END);
sbd.append(mixedBoundaryNextPart).append("--");
sbd.append(LINE_END);
// sbd.append(boundaryNextPart).
// append(LINE_END);
alternativeList.clear();
partSet.clear();
return sbd.toString();
}
④ 如何利用javamail發送帶圖片跟鏈接的郵件
代碼如下:
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class EmailTest {
public static void main(String[] args) throws Exception{
Properties props = new Properties();
props.setProperty("mail.smtp.auth", "true");
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.host", "smtp.163.com");
Session session = Session.getInstance(props,
new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication("xxx","xxx");//這里分別填寫發送email的用戶名、密碼
}
}
);
session.setDebug(true);
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("xxx"));//這里是發送方的email地址如:[email protected]
msg.setSubject("test javamail");
msg.setRecipients(RecipientType.TO,
InternetAddress.parse("xxx"));//這里是接收方的email地址如:[email protected]
msg.setContent("<a href=\"http://www.google.cn\">谷歌</a>","text/html;charset=gb2312");
Transport.send(msg);
}
}
⑤ java 發送郵件
要兩個java文件 還有一個mail.jar是不是只能用javamail誰也不敢說
第一個:
public class Constant {
public static final String mailAddress ="用戶名@163.com";
public static final String mailCount ="用戶名";
public static final String mailPassword ="密碼";
public static final String mailServer ="smtp.163.com";
//pukeyouxintest,
}
第二個:
import java.util.Date;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendMail {
/**
* 發送簡單郵件
* @param str_from:發件人地址
* @param str_to:收件人地址
* @param str_title:郵件標題
* @param str_content:郵件正文
*/
public static void send(String str_from,String str_to,String str_title,String str_content) {
// str_content="<a href='www.163.com'>html元素</a>"; //for testing send html mail!
try {
//建立郵件會話
Properties props=new Properties(); //用來在一個文件中存儲鍵-值對的,其中鍵和值是用等號分隔的,
//存儲發送郵件伺服器的信息
props.put("mail.smtp.host",Constant.mailServer);
//同時通過驗證
props.put("mail.smtp.auth","true");
//根據屬性新建一個郵件會話
Session s=Session.getInstance(props);
s.setDebug(true); //有他會列印一些調試信息。
//由郵件會話新建一個消息對象
MimeMessage message=new MimeMessage(s);
//設置郵件
InternetAddress from= new InternetAddress(str_from); //[email protected]
message.setFrom(from); //設置發件人的地址
//
// //設置收件人,並設置其接收類型為TO
InternetAddress to=new InternetAddress(str_to); //[email protected]
message.setRecipient(Message.RecipientType.TO, to);
//設置標題
message.setSubject(str_title); //java學習
//設置信件內容
// message.setText(str_content); //發送文本郵件 //你好嗎?
message.setContent(str_content, "text/html;charset=gbk"); //發送HTML郵件 //<b>你好</b><br><p>大家好</p>
//設置發信時間
message.setSentDate(new Date());
//存儲郵件信息
message.saveChanges();
//發送郵件
Transport transport=s.getTransport("smtp");
//以smtp方式登錄郵箱,第一個參數是發送郵件用的郵件伺服器SMTP地址,第二個參數為用戶名,第三個參數為密碼
transport.connect(Constant.mailServer,Constant.mailCount,Constant.mailPassword);
//發送郵件,其中第二個參數是所有已設好的收件人地址
transport.sendMessage(message,message.getAllRecipients());
transport.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
//測試用的,你吧你想寫的內容寫上去就行
send(Constant.mailAddress,"收件人郵箱","標題","<b>內容</b>");
}
}
然後把mail.jar導入,就可以了,我用的是163 的,其他的吧相應的伺服器改一下就行了
⑥ 如何用java實現發送html格式的郵件
首先Java發送郵件需要用到JavaMail,先到Oracle官網上下載好最新版本的JavaMail(剛才看了一下,最新是1.5.3),把下載的這個jar文件放到classpath里(如果是Web項目,就放到WEB-INF/lib目錄下。
JavaMail主要支持發送純文本的和html格式的郵件。
發送html格式的郵件的一個常式如下:
importjavax.mail.internet.InternetAddress;
importjavax.mail.internet.MimeMessage;
importjavax.mail.internet.MimeUtility;
importjavax.mail.Session;
importjavax.mail.MessagingException;
importjavax.mail.Transport;
publicclassSendHtmlMail{
publicstaticvoidsendMessage(StringsmtpHost,
Stringfrom,Stringto,
Stringsubject,StringmessageText)
throwsMessagingException,java.io.UnsupportedEncodingException{
//Step1:Configurethemailsession
System.out.println("Configuringmailsessionfor:"+smtpHost);
java.util.Propertiesprops=newjava.util.Properties();
props.setProperty("mail.smtp.auth","true");//指定是否需要SMTP驗證
props.setProperty("mail.smtp.host",smtpHost);//指定SMTP伺服器
props.put("mail.transport.protocol","smtp");
SessionmailSession=Session.getDefaultInstance(props);
mailSession.setDebug(true);//是否在控制台顯示debug信息
//Step2:Constructthemessage
System.out.println("Constructingmessage-from="+from+"to="+to);
InternetAddressfromAddress=newInternetAddress(from);
InternetAddresstoAddress=newInternetAddress(to);
MimeMessagetestMessage=newMimeMessage(mailSession);
testMessage.setFrom(fromAddress);
testMessage.addRecipient(javax.mail.Message.RecipientType.TO,toAddress);
testMessage.setSentDate(newjava.util.Date());
testMessage.setSubject(MimeUtility.encodeText(subject,"gb2312","B"));
testMessage.setContent(messageText,"text/html;charset=gb2312");
System.out.println("Messageconstructed");
//Step3:Nowsendthemessage
Transporttransport=mailSession.getTransport("smtp");
transport.connect(smtpHost,"webmaster","password");
transport.sendMessage(testMessage,testMessage.getAllRecipients());
transport.close();
System.out.println("Messagesent!");
}
publicstaticvoidmain(String[]args){
StringsmtpHost="localhost";
Stringfrom="[email protected]";
Stringto="[email protected]";
Stringsubject="html郵件測試";//subjectjavamail自動轉碼
StringBuffertheMessage=newStringBuffer();
theMessage.append("<h2><fontcolor=red>這倒霉孩子</font></h2>");
theMessage.append("<hr>");
theMessage.append("<i>年年失望年年望</i>");
try{
SendHtmlMail.sendMessage(smtpHost,from,to,subject,theMessage.toString());
}
catch(javax.mail.MessagingExceptionexc){
exc.printStackTrace();
}
catch(java.io.){
exc.printStackTrace();
}
}
}
JavaMail是封裝了很多郵件操作的,所以使用起來不很困難,建議你到JavaMail官網看一下API或下載Java Doc API文檔。
⑦ java 代碼發郵件怎麼添加附件
實現java發送郵件的過程大體有以下幾步:
准備一個properties文件,該文件中存放SMTP伺服器地址等參數。
利用properties創建一個Session對象
利用Session創建Message對象,然後設置郵件主題和正文
利用Transport對象發送郵件
需要的jar有2個:activation.jar和mail.jar發送附件,需要用到Multipart對象。
importjava.io.File;
importjava.io.IOException;
importjava.io.InputStream;
importjava.util.Properties;
importjavax.activation.DataHandler;
importjavax.activation.DataSource;
importjavax.activation.FileDataSource;
importjavax.mail.BodyPart;
importjavax.mail.Message;
importjavax.mail.MessagingException;
importjavax.mail.Multipart;
importjavax.mail.Session;
importjavax.mail.Transport;
importjavax.mail.internet.InternetAddress;
importjavax.mail.internet.MimeBodyPart;
importjavax.mail.internet.MimeMessage;
importjavax.mail.internet.MimeMultipart;
importjavax.mail.internet.MimeUtility;
{
privateMimeMessagemessage;
privateSessionsession;
privateTransporttransport;
privateStringmailHost="";
privateStringsender_username="";
privateStringsender_password="";
privatePropertiesproperties=newProperties();
/*
*初始化方法
*/
publicJavaMailWithAttachment(booleandebug){
InputStreamin=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(IOExceptione){
e.printStackTrace();
}
session=Session.getInstance(properties);
session.setDebug(debug);//開啟後有調試信息
message=newMimeMessage(session);
}
/**
*發送郵件
*
*@paramsubject
*郵件主題
*@paramsendHtml
*郵件內容
*@paramreceiveUser
*收件人地址
*@paramattachment
*附件
*/
publicvoiddoSendHtmlEmail(Stringsubject,StringsendHtml,StringreceiveUser,Fileattachment){
try{
//發件人
InternetAddressfrom=newInternetAddress(sender_username);
message.setFrom(from);
//收件人
InternetAddressto=newInternetAddress(receiveUser);
message.setRecipient(Message.RecipientType.TO,to);
//郵件主題
message.setSubject(subject);
//向multipart對象中添加郵件的各個部分內容,包括文本內容和附件
Multipartmultipart=newMimeMultipart();
//添加郵件正文
BodyPartcontentPart=newMimeBodyPart();
contentPart.setContent(sendHtml,"text/html;charset=UTF-8");
multipart.addBodyPart(contentPart);
//添加附件的內容
if(attachment!=null){
BodyPartattachmentBodyPart=newMimeBodyPart();
DataSourcesource=newFileDataSource(attachment);
attachmentBodyPart.setDataHandler(newDataHandler(source));
//網上流傳的解決文件名亂碼的方法,其實用MimeUtility.encodeWord就可以很方便的搞定
//這里很重要,通過下面的Base64編碼的轉換可以保證你的中文附件標題名在發送時不會變成亂碼
//sun.misc.BASE64Encoderenc=newsun.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("sendsuccess!");
}catch(Exceptione){
e.printStackTrace();
}finally{
if(transport!=null){
try{
transport.close();
}catch(MessagingExceptione){
e.printStackTrace();
}
}
}
}
publicstaticvoidmain(String[]args){
JavaMailWithAttachmentse=newJavaMailWithAttachment(true);
Fileaffix=newFile("c:\測試-test.txt");
se.doSendHtmlEmail("郵件主題","郵件內容","[email protected]",affix);//
}
}