java代码发邮件和附件 java发送邮件添加附件
如何写一个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点虐 .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 ListString to;
/**
* 抄送地址
*/
private ListString cc;
/**
* 暗送地址
*/
private ListString 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 ListMailPart partSet;
private ListMailPart alternativeList;
private String mixedBoundary;
private String mixedBoundaryNextPart;
/**
* 不同类型文件对应的{@link MIME} 类型映射。在添加附件
* {@link #addAttachment(String)} 时,程序会在这个映射中查找对应文件的
* {@link MIME} 类型,如果没有, 则使用
* {@link #defaultAttachmentContentType} 所定义的类型。
*/
private static MapString, 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 HashMapString, 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 ArrayListMailPart();
alternativeList = new ArrayListMailPart();
to = new ArrayListString();
cc = new ArrayListString();
bcc = new ArrayListString();
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();
}
Java发邮件带附件测试通过
package cn bric crm util;
import java util Date;
import java util Enumeration;
import java util Properties;
import java util Vector;
import javax activation *;
import javax mail Authenticator;
import javax mail Message;
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;
import java io FileInputStream;
import java io IOException;
import java text ParseException;
import java util ArrayList;
import java util Date;
import java util HashSet;
import java util Iterator;
import java util List;
import java util Locale;
import java util Set;
import java util regex Pattern;
/**
* p
* Title: 使用javamail发送邮件
* /p
*/
public class MailUtils {
String to = ;// 收件人
String from = ;// 发件人
String host = ;// *** tp主机
String username = ;
String password = ;
String filename = ;// 附件文件名
String subject = ;// 邮件主题
String content = ;// 邮件正文
Vector file = new Vector();// 附件文件集合
/**
* br
* 方法说明 默认构造器 br
* 输入参数 br
* 返回类型
*/
public MailUtils() {
}
/**
* br
* 方法说明 构造器 提供直接的参数传入 br
* 输入参数 br
* 返回类型
*/
public MailUtils(String to String from String *** tpServer
String username String password String subject String content) {
this to = to;
this from = from;
this host = *** tpServer;
this username = username;
this password = password;
this subject = subject;
ntent = content;
}
/**
* br
* 方法说明 设置邮件服务器地址 br
* 输入参数 String host 邮件服务器地址名称 br
* 返回类型
*/
public void setHost(String host) {
this host = host;
}
/**
* br
* 方法说明 设置登录服务器校验密码 br
* 输入参数 br
* 返回类型
*/
public void setPassWord(String pwd) {
this password = pwd;
}
/**
* br
* 方法说明 设置登录服务器校验用户 br
* 输入参数 br
* 返回类型
*/
public void setUserName(String usn) {
this username = usn;
}
/**
* br
* 方法说明 设置邮件发送目的邮箱 br
* 输入参数 br
* 返回类型
*/
public void setTo(String to) {
this to = to;
}
/**
* br
* 方法说明 设置邮件发送源邮箱 br
* 输入参数 br
* 返回类型
*/
public void setFrom(String from) {
this from = from;
}
/**
* br
* 方法说明 设置邮件主题 br
* 输入参数 br
* 返回类型
*/
public void setSubject(String subject) {
this subject = subject;
}
/**
* br
* 方法说明 设置邮件内容 br
* 输入参数 br
* 返回类型
*/
public void setContent(String content) {
ntent = content;
}
/**
* br
* 方法说明 把主题转换为中文 br
* 输入参数 String strText br
* 返回类型
*/
public String transferChinese(String strText) {
try {
strText = MimeUtility encodeText(new String(strText getBytes()
GB ) GB B );
} catch (Exception e) {
e printStackTrace();
}
return strText;
}
/**
* br
* 方法说明 往附件组合中添加附件 br
* 输入参数 br
* 返回类型
*/
public void attachfile(String fname) {
file addElement(fname);
}
/**
* br
* 方法说明 发送邮件 br
* 输入参数 br
* 返回类型 boolean 成功为true 反之为false
*/
public boolean sendMail() {
// 构造mail session
Properties props = new Properties() ;
props put( mail *** tp host host);
props put( mail *** tp auth true );
Session session = Session getDefaultInstance(props
new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username password);
}
});
//Session session = Session getDefaultInstance(props);
// Session session = Session getDefaultInstance(props null);
try {
// 构造MimeMessage 并设定基本的值
MimeMessage msg = new MimeMessage(session);
//MimeMessage msg = new MimeMessage();
msg setFrom(new InternetAddress(from));
//msg addRecipients(Message RecipientType TO address); //这个只能是给一个人发送email
msg setRecipients(Message RecipientType BCC InternetAddress parse(to)) ;
subject = transferChinese(subject);
msg setSubject(subject);
// 构造Multipart
Multipart mp = new MimeMultipart();
// 向Multipart添加正文
MimeBodyPart mbpContent = new MimeBodyPart();
mbpContent setContent(content text/;charset=gb );
// 向MimeMessage添加(Multipart代表正文)
mp addBodyPart(mbpContent);
// 向Multipart添加附件
Enumeration efile = file elements();
while (efile hasMoreElements()) {
MimeBodyPart mbpFile = new MimeBodyPart();
filename = efile nextElement() toString();
FileDataSource fds = new FileDataSource(filename);
mbpFile setDataHandler(new DataHandler(fds));
mbpFile setFileName(fds getName());
// 向MimeMessage添加(Multipart代表附件)
mp addBodyPart(mbpFile);
}
file removeAllElements();
// 向Multipart添加MimeMessage
msg setContent(mp);
msg setSentDate(new Date());
msg saveChanges() ;
// 发送邮件
Transport transport = session getTransport( *** tp );
nnect(host username password);
transport sendMessage(msg msg getAllRecipients());
transport close();
} catch (Exception mex) {
mex printStackTrace();
// Exception ex = null;
// if ((ex = mex getNextException()) != null) {
// ex printStackTrace();
// }
return false;
}
return true;
}
/**
* br
* 方法说明 主方法 用于测试 br
* 输入参数 br
* 返回类型
*/
public static void main(String[] args) {
MailUtils sendmail = new MailUtils();
sendmail setHost( );
sendmail setUserName( se );
sendmail setPassWord( bric );
sendmail setTo( che );
sendmail setFrom( se );
sendmail setSubject( 你好 这是测试! );
sendmail setContent( 你好这是一个带多附件的测试! );
// Mail sendmail = new
// Mail( du_jiang 你好 胃 你好吗? );
sendmail attachfile( d:\\news rar );
sendmail attachfile( d:\\jhjl rar );
System out println(sendmail sendMail());
}
lishixinzhi/Article/program/Java/hx/201311/25753
怎么用java发送带附件的邮件代码详解
package email;
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点虐 .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;
public class Mail {
private static final String LINE_END = "\r\n";
private boolean isDebug = true;
private boolean isAllowReadSocketInfo = true;
private String host;
private String from;
private ListString to;
private ListString cc;
private ListString bcc;
private String subject;
private String user;
private String password;
private String contentType;
private String boundary;
private String boundaryNextPart;
private String contentTransferEncoding;
private String charset;
private String contentDisposition;
private String content;
private String simpleDatePattern;
private String defaultAttachmentContentType;
private ListMailPart partSet;
private static MapString, String contentTypeMap;
static {
// MIME Media Types
contentTypeMap = new HashMapString, 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");
}
private class MailPart extends Mail {
public MailPart() {
}
}
public Mail() {
defaultAttachmentContentType = "application/octet-stream";
simpleDatePattern = "yyyy-MM-dd HH:mm:ss";
boundary = "--=_NextPart_zlz_3907_" + System.currentTimeMillis();
boundaryNextPart = "--" + boundary;
contentTransferEncoding = "base64";
contentType = "multipart/alternative";
charset = Charset.defaultCharset().name();
partSet = new ArrayListMailPart();
to = new ArrayListString();
cc = new ArrayListString();
bcc = new ArrayListString();
}
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;
}
private String toBase64(String str, String charset) {
if (null != str) {
try {
return toBase64(str.getBytes(charset));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return "";
}
private String toBase64(byte[] bs) {
return new BASE64Encoder().encode(bs);
}
private String toBase64(String str) {
return toBase64(str, Charset.defaultCharset().name());
}
private String getAllParts() {
int partCount = partSet.size();
StringBuilder sbd = new StringBuilder(LINE_END);
for (int i = partCount - 1; i = 0; i--) {
Mail attachment = partSet.get(i);
String attachmentContent = attachment.getContent();
if (null != attachmentContent 0 attachmentContent.length()) {
sbd.append(getBoundaryNextPart()).append(LINE_END);
sbd.append("Content-Type: ");
sbd.append(attachment.getContentType());
sbd.append(LINE_END);
sbd.append("Content-Transfer-Encoding: ");
sbd.append(attachment.getContentTransferEncoding());
sbd.append(LINE_END);
if (i != partCount - 1) {
sbd.append("Content-Disposition: ");
sbd.append(attachment.getContentDisposition());
sbd.append(LINE_END);
}
sbd.append(LINE_END);
sbd.append(attachment.getContent());
sbd.append(LINE_END);
}
}
sbd.append(LINE_END);
sbd.append(LINE_END);
partSet.clear();
return sbd.toString();
}
private void addContent() {
if (null != content) {
MailPart part = new MailPart();
part.setContent(toBase64(content));
part.setContentType("text/plain;charset=\"" + charset + "\"");
partSet.add(part);
}
}
private String listToMailString(ListString mailAddressList) {
StringBuilder sbd = new StringBuilder();
if (null != mailAddressList) {
int listSize = mailAddressList.size();
for (int i = 0; i listSize; i++) {
if (0 != i) {
sbd.append(";");
}
sbd.append("").append(mailAddressList.get(i)).append("");
}
}
return sbd.toString();
}
private ListString getrecipient() {
ListString list = new ArrayListString();
list.addAll(to);
list.addAll(cc);
list.addAll(bcc);
return list;
}
public void addAttachment(String filePath) {
addAttachment(filePath, null);
}
public void addTo(String mailAddress) {
this.to.add(mailAddress);
}
public void addCc(String mailAddress) {
this.cc.add(mailAddress);
}
public void addBcc(String mailAddress) {
this.bcc.add(mailAddress);
}
public void addAttachment(String filePath, String charset) {
if (null != filePath filePath.length() 0) {
File file = new File(filePath);
try {
addAttachment(file.getName(), new FileInputStream(file),
charset);
} catch (FileNotFoundException e) {
System.out.println("错误:" + e.getMessage());
System.exit(1);
}
}
}
当前名称:java代码发邮件和附件 java发送邮件添加附件
标题路径:http://hbruida.cn/article/ddjihec.html