① 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);//
}
}