使用JavaMail发送邮件需要用到mailjar和activtionjar两个包。
该类实现了较完整的邮件发送功能,包括以HTML格式发送,添加附件和抄送人。下面是具体的代码:
package cncgwutilmail;import javautilProperties;
import javaxactivationDataHandler;
import javaxactivationFileDataSource;
import javaxmailAddress;
import javaxmailBodyPart;
import javaxmailMessage;
import javaxmailMultipart;
import javaxmailSession;
import javaxmailTransport;
import javaxmailinternetInternetAddress;
import javaxmailinternetMimeBodyPart;
import javaxmailinternetMimeMessage;
import javaxmailinternetMimeMultipart;
public class Mail {
private MimeMessage mimeMsg; //MIME邮件对象
private Session session; //邮件会话对象
private Properties props; //系统属性
private boolean needAuth = false; //smtp是否需要认证
//smtp认证用户名和密码
private String username;
private String password;
private Multipart mp; //Multipart对象,邮件内容,标题,附件等内容均添加到其中后再生成MimeMessage对象
/
Constructor
@param smtp 邮件发送服务器
/
public Mail(String smtp){
setSmtpHost(smtp);
createMimeMessage();
}
/
设置邮件发送服务器
@param hostName String
/
public void setSmtpHost(String hostName) {
Systemoutprintln("设置系统属性:mailsmtphost = "+hostName);
if(props == null)
props = SystemgetProperties(); //获得系统属性对象
propsput("mailsmtphost",hostName); //设置SMTP主机
}
/
创建MIME邮件对象
@return
/
public boolean createMimeMessage()
{
try {
Systemoutprintln("准备获取邮件会话对象!");
session = SessiongetDefaultInstance(props,null); //获得邮件会话对象
}
catch(Exception e){
Systemerrprintln("获取邮件会话对象时发生错误!"+e);
return false;
}
Systemoutprintln("准备创建MIME邮件对象!");
try {
mimeMsg = new MimeMessage(session); //创建MIME邮件对象
mp = new MimeMultipart();
return true;
} catch(Exception e){
Systemerrprintln("创建MIME邮件对象失败!"+e);
return false;
}
}
/
设置SMTP是否需要验证
@param need
/
public void setNeedAuth(boolean need) {
Systemoutprintln("设置smtp身份认证:mailsmtpauth = "+need);
if(props == null) props = SystemgetProperties();
if(need){
propsput("mailsmtpauth","true");
}else{
propsput("mailsmtpauth","false");
}
}
/
设置用户名和密码
@param name
@param pass
/
public void setNamePass(String name,String pass) {
username = name;
password = pass;
}
/
设置邮件主题
@param mailSubject
@return
/
public boolean setSubject(String mailSubject) {
Systemoutprintln("设置邮件主题!");
try{
mimeMsgsetSubject(mailSubject);
return true;
}
catch(Exception e) {
Systemerrprintln("设置邮件主题发生错误!");
return false;
}
}
/
设置邮件正文
@param mailBody String
/
public boolean setBody(String mailBody) {
try{
BodyPart bp = new MimeBodyPart();
bpsetContent(""+mailBody,"text/html;charset=GBK");
mpaddBodyPart(bp);
return true;
} catch(Exception e){
Systemerrprintln("设置邮件正文时发生错误!"+e);
return false;
}
}
/
添加附件
@param filename String
/
public boolean addFileAffix(String filename) {
Systemoutprintln("增加邮件附件:"+filename);
try{
BodyPart bp = new MimeBodyPart();
FileDataSource fileds = new FileDataSource(filename);
bpsetDataHandler(new DataHandler(fileds));
bpsetFileName(filedsgetName());
mpaddBodyPart(bp);
return true;
} catch(Exception e){
Systemerrprintln("增加邮件附件:"+filename+"发生错误!"+e);
return false;
}
}
/
设置发信人
@param from String
/
public boolean setFrom(String from) {
Systemoutprintln("设置发信人!");
try{
mimeMsgsetFrom(new InternetAddress(from)); //设置发信人
return true;
} catch(Exception e) {
return false;
}
}
/
设置收信人
@param to String
/
public boolean setTo(String to){
if(to == null)return false;
try{
mimeMsgsetRecipients(MessageRecipientTypeTO,InternetAddressparse(to));
return true;
} catch(Exception e) {
return false;
}
}
/
设置抄送人
@param copyto String
/
public boolean setCopyTo(String copyto)
{
if(copyto == null)return false;
try{
mimeMsgsetRecipients(MessageRecipientTypeCC,(Address[])InternetAddressparse(copyto));
return true;
}
catch(Exception e)
{ return false; }
}
/
发送邮件
/
public boolean sendOut()
{
try{
mimeMsgsetContent(mp);
mimeMsgsaveChanges();
Systemoutprintln("正在发送邮件");
Session mailSession = SessiongetInstance(props,null);
Transport transport = mailSessiongetTransport("smtp");
transportconnect((String)propsget("mailsmtphost"),username,password);
transportsendMessage(mimeMsg,mimeMsggetRecipients(MessageRecipientTypeTO));
transportsendMessage(mimeMsg,mimeMsggetRecipients(MessageRecipientTypeCC));
//transportsend(mimeMsg);
Systemoutprintln("发送邮件成功!");
transportclose();
return true;
} catch(Exception e) {
Systemerrprintln("邮件发送失败!"+e);
return false;
}
}
/
调用sendOut方法完成邮件发送
@param smtp
@param from
@param to
@param subject
@param content
@param username
@param password
@return boolean
/
public static boolean send(String smtp,String from,String to,String subject,String content,String username,String password) {
Mail theMail = new Mail(smtp);
theMailsetNeedAuth(true); //需要验证
if(!theMailsetSubject(subject)) return false;
if(!theMailsetBody(content)) return false;
if(!theMailsetTo(to)) return false;
if(!theMailsetFrom(from)) return false;
theMailsetNamePass(username,password);
if(!theMailsendOut()) return false;
return true;
}
/
调用sendOut方法完成邮件发送,带抄送
@param smtp
@param from
@param to
@param copyto
@param subject
@param content
@param username
@param password
@return boolean
/
public static boolean sendAndCc(String smtp,String from,String to,String copyto,String subject,String content,String username,String password) {
Mail theMail = new Mail(smtp);
theMailsetNeedAuth(true); //需要验证
if(!theMailsetSubject(subject)) return false;
if(!theMailsetBody(content)) return false;
if(!theMailsetTo(to)) return false;
if(!theMailsetCopyTo(copyto)) return false;
if(!theMailsetFrom(from)) return false;
theMailsetNamePass(username,password);
if(!theMailsendOut()) return false;
return true;
}
/
调用sendOut方法完成邮件发送,带附件
@param smtp
@param from
@param to
@param subject
@param content
@param username
@param password
@param filename 附件路径
@return
/
public static boolean send(String smtp,String from,String to,String subject,String content,String username,String password,String filename) {
Mail theMail = new Mail(smtp);
theMailsetNeedAuth(true); //需要验证
if(!theMailsetSubject(subject)) return false;
if(!theMailsetBody(content)) return false;
if(!theMailaddFileAffix(filename)) return false;
if(!theMailsetTo(to)) return false;
if(!theMailsetFrom(from)) return false;
theMailsetNamePass(username,password);
if(!theMailsendOut()) return false;
return true;
}
/
调用sendOut方法完成邮件发送,带附件和抄送
@param smtp
@param from
@param to
@param copyto
@param subject
@param content
@param username
@param password
@param filename
@return
/
public static boolean sendAndCc(String smtp,String from,String to,String copyto,String subject,String content,String username,String password,String filename) {
Mail theMail = new Mail(smtp);
theMailsetNeedAuth(true); //需要验证
if(!theMailsetSubject(subject)) return false;
if(!theMailsetBody(content)) return false;
if(!theMailaddFileAffix(filename)) return false;
if(!theMailsetTo(to)) return false;
if(!theMailsetCopyTo(copyto)) return false;
if(!theMailsetFrom(from)) return false;
theMailsetNamePass(username,password);
if(!theMailsendOut()) return false;
return true;
}
}1要想效率发邮件可以用多线程每个线程发指定批量的邮件
2要想不被查封为垃圾邮件,这个就有很多地方要注意了
邮件的内容不要含有太多信息,内容尽量简洁,不要涉及一些秽色情的东西。
不要向同一个人发送同样的邮件。
发邮件时ip最好用代理每发送个50封邮件就换个ip,因为邮件服务器也会检查你ip在这么短时间发了这么多邮件也会认为你是恶意群发。
最好能加入邮件接收者的白名单或订阅名单package bydcore;
import javaioBufferedReader;
import javaioFile;
import javaioFileInputStream;
import javaioFileNotFoundException;
import javaioIOException;
import javaioInputStream;
import javaioInputStreamReader;
import javaioPrintWriter;
import javaioUnsupportedEncodingException;
import javanetSocket;
import javaniocharsetCharset;
import javatextSimpleDateFormat;
import javautilArrayList;
import javautilDate;
import javautilHashMap;
import javautilList;
import javautilMap;
import sunmiscBASE64Encoder;
/
该类使用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) {
thisv = v;
}
public String getValue() {
return thisv;
}
}
static {
// MIME Media Types
contentTypeMap = new HashMap<String, String>();
contentTypeMapput("xls", "application/vndms-excel");
contentTypeMapput("xlsx", "application/vndms-excel");
contentTypeMapput("xlsm", "application/vndms-excel");
contentTypeMapput("xlsb", "application/vndms-excel");
contentTypeMapput("doc", "application/msword");
contentTypeMapput("dot", "application/msword");
contentTypeMapput("docx", "application/msword");
contentTypeMapput("docm", "application/msword");
contentTypeMapput("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_" + SystemcurrentTimeMillis();
boundaryNextPart = "--" + boundary;
contentTransferEncoding = "base64";
contentType = "multipart/mixed";
charset = CharsetdefaultCharset()name();
partSet = new ArrayList<MailPart>();
alternativeList = new ArrayList<MailPart>();
to = new ArrayList<String>();
cc = new ArrayList<String>();
bcc = new ArrayList<String>();
mixedBoundary = "=NextAttachment_zlz_" + SystemcurrentTimeMillis();
mixedBoundaryNextPart = "--" + mixedBoundary;
}
/
根据指定的完整文件名在 {@link #contentTypeMap} 中查找其相应的MIME类型,
如果没找到,则返回 {@link #defaultAttachmentContentType}
所指定的默认类型。
@param fileName
文件名
@return 返回文件对应的MIME类型。
/
private String getPartContentType(String fileName) {
String ret = null;
if (null != fileName) {
int flag = fileNamelastIndexOf("");
if (0 <= flag && flag < fileNamelength() - 1) {
fileName = fileNamesubstring(flag + 1);
}
ret = contentTypeMapget(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(strgetBytes(charset));
} catch (UnsupportedEncodingException e) {
eprintStackTrace();
}
}
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, CharsetdefaultCharset()name());
}
/
将所有的邮件单元按照标准的MIME格式要求合并。
@return 返回一个所有单元合并后的字符串。
/
private String getAllParts() {
StringBuilder sbd = new StringBuilder(LINE_END);
sbdappend(mixedBoundaryNextPart);
sbdappend(LINE_END);
sbdappend("Content-Type: ");
sbdappend("multipart/alternative");
sbdappend(";");
sbdappend("boundary=\"");
sbdappend(boundary)append("\""); // 邮件类型设置
sbdappend(LINE_END);
sbdappend(LINE_END);
sbdappend(LINE_END);
addPartsToString(alternativeList, sbd, getBoundaryNextPart());
sbdappend(getBoundaryNextPart())append("--");
sbdappend(LINE_END);
addPartsToString(partSet, sbd, mixedBoundaryNextPart);
sbdappend(LINE_END);
sbdappend(mixedBoundaryNextPart)append("--");
sbdappend(LINE_END);
// sbdappend(boundaryNextPart)
// append(LINE_END);
alternativeListclear();
partSetclear();
return sbdtoString();
}你只是发邮件不是做邮件服务器吧?这样的话 在linux和window没有区别不然java都不好意思说自己是跨平台的了
JAVA邮件发送的大致过程是这样的的:
1、构建一个继承自javaxmailAuthenticator的具体类,并重写里面的getPasswordAuthentication()方法。此类是用作登录校验的,以确保你对该邮箱有发送邮件的权利。
2、构建一个properties文件,该文件中存放SMTP服务器地址等参数。
3、通过构建的properties文件和javaxmailAuthenticator具体类来创建一个javaxmailSession。Session的创建,就相当于登录邮箱一样。剩下的自然就是新建邮件。
4、构建邮件内容,一般是javaxmailinternetMimeMessage对象,并指定发送人,收信人,主题,内容等等。
5、使用javaxmailTransport工具类发送邮件。
参考地址>
首先Java发送邮件需要用到JavaMail,先到Oracle官网上下载好最新版本的JavaMail(刚才看了一下,最新是153),把下载的这个jar文件放到classpath里(如果是Web项目,就放到WEB-INF/lib目录下。
JavaMail主要支持发送纯文本的和html格式的邮件。
发送html格式的邮件的一个例程如下:
import javaxmailinternetInternetAddress;import javaxmailinternetMimeMessage;
import javaxmailinternetMimeUtility;
import javaxmailSession;
import javaxmailMessagingException;
import javaxmailTransport;
public class SendHtmlMail {
public static void sendMessage(String smtpHost,
String from, String to,
String subject, String messageText)
throws MessagingException,javaioUnsupportedEncodingException {
// Step 1: Configure the mail session
Systemoutprintln("Configuring mail session for: " + smtpHost);
javautilProperties props = new javautilProperties();
propssetProperty("mailsmtpauth", "true");//指定是否需要SMTP验证
propssetProperty("mailsmtphost", smtpHost);//指定SMTP服务器
propsput("mailtransportprotocol", "smtp");
Session mailSession = SessiongetDefaultInstance(props);
mailSessionsetDebug(true);//是否在控制台显示debug信息
// Step 2: Construct the message
Systemoutprintln("Constructing message - from=" + from + " to=" + to);
InternetAddress fromAddress = new InternetAddress(from);
InternetAddress toAddress = new InternetAddress(to);
MimeMessage testMessage = new MimeMessage(mailSession);
testMessagesetFrom(fromAddress);
testMessageaddRecipient(javaxmailMessageRecipientTypeTO, toAddress);
testMessagesetSentDate(new javautilDate());
testMessagesetSubject(MimeUtilityencodeText(subject,"gb2312","B"));
testMessagesetContent(messageText, "text/html;charset=gb2312");
Systemoutprintln("Message constructed");
// Step 3: Now send the message
Transport transport = mailSessiongetTransport("smtp");
transportconnect(smtpHost, "webmaster", "password");
transportsendMessage(testMessage, testMessagegetAllRecipients());
transportclose();
Systemoutprintln("Message sent!");
}
public static void main(String[] args) {
String smtpHost = "localhost";
String from = "webmaster@mymailcom";
String to = "mfc42d@sohucom";
String subject = "html邮件测试"; //subject javamail自动转码
StringBuffer theMessage = new StringBuffer();
theMessageappend("<h2><font color=red>这倒霉孩子</font></h2>");
theMessageappend("<hr>");
theMessageappend("<i>年年失望年年望</i>");
try {
SendHtmlMailsendMessage(smtpHost, from, to, subject, theMessagetoString());
}
catch (javaxmailMessagingException exc) {
excprintStackTrace();
}
catch (javaioUnsupportedEncodingException exc) {
excprintStackTrace();
}
}
}
JavaMail是封装了很多邮件 *** 作的,所以使用起来不很困难,建议你到JavaMail官网看一下API或下载Java Doc API文档。
public boolean sendTextMail(MailSenderInfo mailInfo) {// 判断是否需要身份认证
MyAuthenticator authenticator = null;
Properties pro = mailInfogetProperties();
if (mailInfoisValidate()) {
// 如果需要身份认证,则创建一个密码验证器
authenticator = new MyAuthenticator(mailInfogetUserName(), mailInfogetPassword());
}
// 根据邮件会话属性和密码验证器构造一个发送邮件的session
Session sendMailSession = null;
//sendMailSession = SessiongetDefaultInstance(pro,authenticator); //获取默认可能报错
sendMailSession = SessiongetInstance(pro,authenticator);//新创建一个session
if (sendMailSession==null){
Systemoutprintln("无法获取邮件邮件Session");
}
try {
// 根据session创建一个邮件消息
Message mailMessage = new MimeMessage(sendMailSession);
// 创建邮件发送者地址
Address from = new InternetAddress(mailInfogetFromAddress());
// 设置邮件消息的发送者
mailMessagesetFrom(from);
// 创建邮件的接收者地址,并设置到邮件消息中
Address to = new InternetAddress(mailInfogetToAddress());
mailMessagesetRecipient(MessageRecipientTypeTO,to);
// 设置邮件消息的主题
mailMessagesetSubject(mailInfogetSubject());
// 设置邮件消息发送的时间
mailMessagesetSentDate(new Date());
// 设置邮件消息的主要内容
String mailContent = mailInfogetContent();
mailMessagesetText(mailContent);
//添加附件
// if(mailInfogetAttachFileNames()!=null || mailInfogetAttachFileNames()length>0){
// Multipart mp = new MimeMultipart();
// MimeBodyPart mbp=null;
// for(String fileName:mailInfogetAttachFileNames()){
// mbp=new MimeBodyPart();
// FileDataSource fds=new FileDataSource(fileName); //得到数据源
// mbpsetDataHandler(new DataHandler(fds)); //得到附件本身并至入BodyPart
// mbpsetFileName(fdsgetName()); //得到文件名同样至入BodyPart
// mpaddBodyPart(mbp);
// }
// mailMessagesetContent(mp);
// }
// 发送邮件
Transportsend(mailMessage);
return true;
} catch (MessagingException ex) {
exprintStackTrace();
}
return false;
}
public class MailSenderInfo {
// 发送邮件的服务器的IP和端口
private String mailServerHost;
private String mailServerPort = "25";
// 邮件发送者的地址
private String fromAddress;
// 邮件接收者的地址
private String toAddress;
// 登陆邮件发送服务器的用户名和密码
private String userName;
private String password;
// 是否需要身份验证
private boolean validate = false;
// 邮件主题
private String subject;
// 邮件的文本内容
private String content;
// 邮件附件的文件名
private String[] attachFileNames;
//邮件抄送人
private List<String> ccUserList;
/ //
获得邮件会话属性
/
public Properties getProperties(){
Properties p = new Properties();
pput("mailsmtphost", thismailServerHost);
pput("mailsmtpport", thismailServerPort);
pput("mailsmtpauth", validate "true" : "false");
return p;
}
public String getMailServerHost() {
return mailServerHost;
}
public void setMailServerHost(String mailServerHost) {
thismailServerHost = mailServerHost;
}
public String getMailServerPort() {
return mailServerPort;
}
public void setMailServerPort(String mailServerPort) {
thismailServerPort = mailServerPort;
}
public boolean isValidate() {
return validate;
}
public void setValidate(boolean validate) {
thisvalidate = validate;
}
public String[] getAttachFileNames() {
return attachFileNames;
}
public void setAttachFileNames(String[] fileNames) {
thisattachFileNames = fileNames;
}
public String getFromAddress() {
return fromAddress;
}
public void setFromAddress(String fromAddress) {
thisfromAddress = fromAddress;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
thispassword = password;
}
public String getToAddress() {
return toAddress;
}
public void setToAddress(String toAddress) {
thistoAddress = toAddress;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
thisuserName = userName;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
thissubject = subject;
}
public String getContent() {
return content;
}
public void setContent(String textContent) {
thiscontent = textContent;
}
public List<String> getCcUserList(){
return ccUserList;
}
public void setCcUserList(List<String> ccUserList){
thisccUserList = ccUserList;
}
}
public static void main(String[] args) {
// 这个类主要是设置邮件
MailSenderInfo mailInfo = new MailSenderInfo();
mailInfosetMailServerHost("smtp163com");
mailInfosetMailServerPort("25");
mailInfosetValidate(true);
mailInfosetUserName("zhengzhanzong@163com");
mailInfosetPassword("zzzong0828");// 您的邮箱密码
mailInfosetFromAddress("");
//接受方信息
mailInfosetToAddress("");
mailInfosetSubject("邮箱标题 ");
mailInfosetContent("设置邮箱内容 如> }
这样发
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)