十年网站开发经验 + 多家企业客户 + 靠谱的建站团队
量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决
第一个类:MailSenderInfo.java
成都创新互联公司专注于武汉网站建设服务及定制,我们拥有丰富的企业做网站经验。 热诚为您提供武汉营销型网站建设,武汉网站制作、武汉网页设计、武汉网站官网定制、微信小程序服务,打造武汉网络公司原创品牌,更为您提供武汉网站排名全网营销落地服务。
[java] view plain copy
package com.util.mail;
/**
* 发送邮件需要使用的基本信息
*author by wangfun
小说520
*/
import java.util.Properties;
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;
/**
* 获得邮件会话属性
*/
public Properties getProperties(){
Properties p = new Properties();
p.put("mail.smtp.host", this.mailServerHost);
p.put("mail.smtp.port", this.mailServerPort);
p.put("mail.smtp.auth", validate ? "true" : "false");
return p;
}
public String getMailServerHost() {
return mailServerHost;
}
public void setMailServerHost(String mailServerHost) {
this.mailServerHost = mailServerHost;
}
public String getMailServerPort() {
return mailServerPort;
}
public void setMailServerPort(String mailServerPort) {
this.mailServerPort = mailServerPort;
}
public boolean isValidate() {
return validate;
}
public void setValidate(boolean validate) {
this.validate = validate;
}
public String[] getAttachFileNames() {
return attachFileNames;
}
public void setAttachFileNames(String[] fileNames) {
this.attachFileNames = fileNames;
}
public String getFromAddress() {
return fromAddress;
}
public void setFromAddress(String fromAddress) {
this.fromAddress = fromAddress;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getToAddress() {
return toAddress;
}
public void setToAddress(String toAddress) {
this.toAddress = toAddress;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getContent() {
return content;
}
public void setContent(String textContent) {
this.content = textContent;
}
}
第二个类:SimpleMailSender.java
[java] view plain copy
package com.util.mail;
import java.util.Date;
import java.util.Properties;
import javax.mail.Address;
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;
/**
* 简单邮件(不带附件的邮件)发送器
BT下载
*/
public class SimpleMailSender {
/**
* 以文本格式发送邮件
* @param mailInfo 待发送的邮件的信息
*/
public boolean sendTextMail(MailSenderInfo mailInfo) {
// 判断是否需要身份认证
MyAuthenticator authenticator = null;
Properties pro = mailInfo.getProperties();
if (mailInfo.isValidate()) {
// 如果需要身份认证,则创建一个密码验证器
authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
}
// 根据邮件会话属性和密码验证器构造一个发送邮件的session
Session sendMailSession = Session.getDefaultInstance(pro,authenticator);
try {
// 根据session创建一个邮件消息
Message mailMessage = new MimeMessage(sendMailSession);
// 创建邮件发送者地址
Address from = new InternetAddress(mailInfo.getFromAddress());
// 设置邮件消息的发送者
mailMessage.setFrom(from);
// 创建邮件的接收者地址,并设置到邮件消息中
Address to = new InternetAddress(mailInfo.getToAddress());
mailMessage.setRecipient(Message.RecipientType.TO,to);
// 设置邮件消息的主题
mailMessage.setSubject(mailInfo.getSubject());
// 设置邮件消息发送的时间
mailMessage.setSentDate(new Date());
// 设置邮件消息的主要内容
String mailContent = mailInfo.getContent();
mailMessage.setText(mailContent);
// 发送邮件
Transport.send(mailMessage);
return true;
} catch (MessagingException ex) {
ex.printStackTrace();
}
return false;
}
/**
* 以HTML格式发送邮件
* @param mailInfo 待发送的邮件信息
*/
public static boolean sendHtmlMail(MailSenderInfo mailInfo){
// 判断是否需要身份认证
MyAuthenticator authenticator = null;
Properties pro = mailInfo.getProperties();
//如果需要身份认证,则创建一个密码验证器
if (mailInfo.isValidate()) {
authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
}
// 根据邮件会话属性和密码验证器构造一个发送邮件的session
Session sendMailSession = Session.getDefaultInstance(pro,authenticator);
try {
// 根据session创建一个邮件消息
Message mailMessage = new MimeMessage(sendMailSession);
// 创建邮件发送者地址
Address from = new InternetAddress(mailInfo.getFromAddress());
// 设置邮件消息的发送者
mailMessage.setFrom(from);
// 创建邮件的接收者地址,并设置到邮件消息中
Address to = new InternetAddress(mailInfo.getToAddress());
// Message.RecipientType.TO属性表示接收者的类型为TO
mailMessage.setRecipient(Message.RecipientType.TO,to);
// 设置邮件消息的主题
mailMessage.setSubject(mailInfo.getSubject());
// 设置邮件消息发送的时间
mailMessage.setSentDate(new Date());
// MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象
Multipart mainPart = new MimeMultipart();
// 创建一个包含HTML内容的MimeBodyPart
BodyPart html = new MimeBodyPart();
// 设置HTML内容
html.setContent(mailInfo.getContent(), "text/html; charset=utf-8");
mainPart.addBodyPart(html);
// 将MiniMultipart对象设置为邮件内容
mailMessage.setContent(mainPart);
// 发送邮件
Transport.send(mailMessage);
return true;
} catch (MessagingException ex) {
ex.printStackTrace();
}
return false;
}
}
第三个类:MyAuthenticator.java
[java] view plain copy
package com.util.mail;
import javax.mail.*;
public class MyAuthenticator extends Authenticator{
String userName=null;
String password=null;
public MyAuthenticator(){
}
public MyAuthenticator(String username, String password) {
this.userName = username;
this.password = password;
}
protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(userName, password);
}
}
下面给出使用上面三个类的代码:
[java] view plain copy
public static void main(String[] args){
//这个类主要是设置邮件
MailSenderInfo mailInfo = new MailSenderInfo();
mailInfo.setMailServerHost("smtp.163.com");
mailInfo.setMailServerPort("25");
mailInfo.setValidate(true);
mailInfo.setUserName("han2000lei@163.com");
mailInfo.setPassword("**********");//您的邮箱密码
mailInfo.setFromAddress("han2000lei@163.com");
mailInfo.setToAddress("han2000lei@163.com");
mailInfo.setSubject("设置邮箱标题 如 中国桂花网");
mailInfo.setContent("设置邮箱内容 如 中国桂花网 是中国最大桂花网站==");
//这个类主要来发送邮件
SimpleMailSender sms = new SimpleMailSender();
sms.sendTextMail(mailInfo);//发送文体格式
sms.sendHtmlMail(mailInfo);//发送html格式
}
最后,给出朋友们几个注意的地方:
1、使用此代码你可以完成你的javamail的邮件发送功能。三个类缺一不可。
2、这三个类我打包是用的com.util.mail包,如果不喜欢,你可以自己改,但三个类文件必须在同一个包中
3、不要使用你刚刚注册过的邮箱在程序中发邮件,如果你的163邮箱是刚注册不久,那你就不要使用“smtp.163.com”。因为你发不出去。刚注册的邮箱是不会给你这种权限的,也就是你不能通过验证。要使用你经常用的邮箱,而且时间比较长的。
4、另一个问题就是mailInfo.setMailServerHost("smtp.163.com");与mailInfo.setFromAddress("han2000lei@163.com");这两句话。即如果你使用163smtp服务器,那么发送邮件地址就必须用163的邮箱,如果不的话,是不会发送成功的。
5、关于javamail验证错误的问题,网上的解释有很多,但我看见的只有一个。就是我的第三个类。你只要复制全了代码,我想是不会有问题的。
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.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;
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);
}
}
}
发送的邮件内容Tabletrtd邮件内容/td/tr/table 接收的时候会自动转成HTML页面的 发送的时候就像页面排版的内容一样的发过去就好了
java 开源项目这样解释 Commons-Email:
Commons-Email的目的是提供一组用于发送Email的API,它基于Java Mail API基础之上并进行了简化。它提供的主要Java类有:SimpleEmail:这个类用于发送简单的文本类型email。MultiPartEmail:这个类允许发送文本消息并附带附件。HtmlEmail:用于发送Html格式的附件并支持内含图片。EmailAttachment:这是一个简单的容器类用于简化附件的处理。
main方法就不说了;
Email email = new SimpleEmail();//创建简单的文本类型email对象
email.setHostName(map.get("hostname"));//设置邮件服务器
email.setSmtpPort(Integer.parseInt(map.get("port")));//设置SMTP协议端口,邮件发送一般默认是25
email.setAuthenticator(new DefaultAuthenticator(map.get("username"), map.get("password")));////邮件服务器验证:用户名/密码
email.setFrom(map.get("from"));//发送人
email.setSubject(map.get("subject"));邮件标题
email.setMsg(map.get("msg"));//邮件内容
for(String to: map.get("to").split(";")) {
email.addTo(to);//收件人
}
使用JavaMail发送邮件需要用到mail.jar和activtion.jar两个包。
该类实现了较完整的邮件发送功能,包括以HTML格式发送,添加附件和抄送人。下面是具体的代码:
package cn.cgw.util.mail;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Message;
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;
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) {
System.out.println("设置系统属性:mail.smtp.host = "+hostName);
if(props == null)
props = System.getProperties(); //获得系统属性对象
props.put("mail.smtp.host",hostName); //设置SMTP主机
}
/**
* 创建MIME邮件对象
* @return
*/
public boolean createMimeMessage()
{
try {
System.out.println("准备获取邮件会话对象!");
session = Session.getDefaultInstance(props,null); //获得邮件会话对象
}
catch(Exception e){
System.err.println("获取邮件会话对象时发生错误!"+e);
return false;
}
System.out.println("准备创建MIME邮件对象!");
try {
mimeMsg = new MimeMessage(session); //创建MIME邮件对象
mp = new MimeMultipart();
return true;
} catch(Exception e){
System.err.println("创建MIME邮件对象失败!"+e);
return false;
}
}
/**
* 设置SMTP是否需要验证
* @param need
*/
public void setNeedAuth(boolean need) {
System.out.println("设置smtp身份认证:mail.smtp.auth = "+need);
if(props == null) props = System.getProperties();
if(need){
props.put("mail.smtp.auth","true");
}else{
props.put("mail.smtp.auth","false");
}
}
/**
* 设置用户名和密码
* @param name
* @param pass
*/
public void setNamePass(String name,String pass) {
username = name;
password = pass;
}
/**
* 设置邮件主题
* @param mailSubject
* @return
*/
public boolean setSubject(String mailSubject) {
System.out.println("设置邮件主题!");
try{
mimeMsg.setSubject(mailSubject);
return true;
}
catch(Exception e) {
System.err.println("设置邮件主题发生错误!");
return false;
}
}
/**
* 设置邮件正文
* @param mailBody String
*/
public boolean setBody(String mailBody) {
try{
BodyPart bp = new MimeBodyPart();
bp.setContent(""+mailBody,"text/html;charset=GBK");
mp.addBodyPart(bp);
return true;
} catch(Exception e){
System.err.println("设置邮件正文时发生错误!"+e);
return false;
}
}
/**
* 添加附件
* @param filename String
*/
public boolean addFileAffix(String filename) {
System.out.println("增加邮件附件:"+filename);
try{
BodyPart bp = new MimeBodyPart();
FileDataSource fileds = new FileDataSource(filename);
bp.setDataHandler(new DataHandler(fileds));
bp.setFileName(fileds.getName());
mp.addBodyPart(bp);
return true;
} catch(Exception e){
System.err.println("增加邮件附件:"+filename+"发生错误!"+e);
return false;
}
}
/**
* 设置发信人
* @param from String
*/
public boolean setFrom(String from) {
System.out.println("设置发信人!");
try{
mimeMsg.setFrom(new InternetAddress(from)); //设置发信人
return true;
} catch(Exception e) {
return false;
}
}
/**
* 设置收信人
* @param to String
*/
public boolean setTo(String to){
if(to == null)return false;
try{
mimeMsg.setRecipients(Message.RecipientType.TO,InternetAddress.parse(to));
return true;
} catch(Exception e) {
return false;
}
}
/**
* 设置抄送人
* @param copyto String
*/
public boolean setCopyTo(String copyto)
{
if(copyto == null)return false;
try{
mimeMsg.setRecipients(Message.RecipientType.CC,(Address[])InternetAddress.parse(copyto));
return true;
}
catch(Exception e)
{ return false; }
}
/**
* 发送邮件
*/
public boolean sendOut()
{
try{
mimeMsg.setContent(mp);
mimeMsg.saveChanges();
System.out.println("正在发送邮件....");
Session mailSession = Session.getInstance(props,null);
Transport transport = mailSession.getTransport("smtp");
transport.connect((String)props.get("mail.smtp.host"),username,password);
transport.sendMessage(mimeMsg,mimeMsg.getRecipients(Message.RecipientType.TO));
transport.sendMessage(mimeMsg,mimeMsg.getRecipients(Message.RecipientType.CC));
//transport.send(mimeMsg);
System.out.println("发送邮件成功!");
transport.close();
return true;
} catch(Exception e) {
System.err.println("邮件发送失败!"+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);
theMail.setNeedAuth(true); //需要验证
if(!theMail.setSubject(subject)) return false;
if(!theMail.setBody(content)) return false;
if(!theMail.setTo(to)) return false;
if(!theMail.setFrom(from)) return false;
theMail.setNamePass(username,password);
if(!theMail.sendOut()) 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);
theMail.setNeedAuth(true); //需要验证
if(!theMail.setSubject(subject)) return false;
if(!theMail.setBody(content)) return false;
if(!theMail.setTo(to)) return false;
if(!theMail.setCopyTo(copyto)) return false;
if(!theMail.setFrom(from)) return false;
theMail.setNamePass(username,password);
if(!theMail.sendOut()) 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);
theMail.setNeedAuth(true); //需要验证
if(!theMail.setSubject(subject)) return false;
if(!theMail.setBody(content)) return false;
if(!theMail.addFileAffix(filename)) return false;
if(!theMail.setTo(to)) return false;
if(!theMail.setFrom(from)) return false;
theMail.setNamePass(username,password);
if(!theMail.sendOut()) 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);
theMail.setNeedAuth(true); //需要验证
if(!theMail.setSubject(subject)) return false;
if(!theMail.setBody(content)) return false;
if(!theMail.addFileAffix(filename)) return false;
if(!theMail.setTo(to)) return false;
if(!theMail.setCopyTo(copyto)) return false;
if(!theMail.setFrom(from)) return false;
theMail.setNamePass(username,password);
if(!theMail.sendOut()) return false;
return true;
}
}
我们要用DOMINO5R的例子重写一下:
rti.embedObject(EmbeddedObject.EMBED_ATTACHMENT, null,
attachFilePath, attachFilePath); // 添加附件
注:其中rti = (RichTextItem) memo.createRichTextItem("Body");
让邮件带上附件就一句话,很简单吧。
如果,你不明白其中的参数,还是会搞不出来,一个字晕!
其中前两个参数我就不说了,第三个和第四个参数写成一样就可以了。
强烈注意:
1* 添加的附件必须放在DOMINO服务器上,不能放在客户端添加附件,不要问为什么,这是事实。你在客户端的硬盘上无论放在哪,它也不让你上传。
2*我们的项目环境,DOMINO是运行在AS400上,它的安装目录是em_01,我们就假设把附件放在AS400 的em_01/test/test.tar,在程序使用相对路径,"test/test.tar"相对于邮件的根目录em_01.
如果,按我说的做法应该不会有问题了。若想看一个完整例子,请参考我的“java在收。发lotus邮件的实例了”。