这是我基于一个网上的代码自己修改封装过来的.
你可以参考一下
/**
*
* @author Sglee
*
*/
public class SimpleMail {
private static String encode = null
static {
if ("\\".equals(File.separator)) {
encode = "GBK"
} else {
encode = "UTF-8"
}
}
/**
* 以文本格式发送邮件
*
* @param mailInfo
* @return
*/
public static boolean sendTextMail(MailInfo mailInfo) {
for (int i = 0 i < 3 i++) {
// 判断是否需要身份认证
MyAuthenticator authenticator = null
Properties properties = mailInfo.getProperties()
if (mailInfo.isValidate()) {
// 如果需要身份认证,则创建一个密码验证器
authenticator = new MyAuthenticator(mailInfo.getUsername(),
mailInfo.getPassword())
}
// 根据邮件会话属性和密码验证器构造一个发送邮件的session
Session sendMailSession = Session.getDefaultInstance(properties,
authenticator)
if (mailInfo.isDebug()) {
sendMailSession.setDebug(true)
}
try {
Message mailMessage = new MimeMessage(sendMailSession)// 根据session创建一个邮件消息
Address from = new InternetAddress(mailInfo.getFromAddress())// 创建邮件发送者地址
mailMessage.setFrom(from)// 设置邮件消息的发送者
// Address to = new InternetAddress(mailInfo.getToAddress())//
// 创建邮件的接收者地址
// mailMessage.setRecipient(Message.RecipientType.TO, to)//
// 设置邮件消息的接收者
mailMessage.setRecipients(Message.RecipientType.TO,
wrapAddress(mailInfo.getToAddress()))
// InternetAddress ms = new
// InternetAddress(mailInfo.getMsAddress())
// mailMessage.setRecipient(Message.RecipientType.BCC, ms) //
// 密送人
mailMessage.setRecipients(Message.RecipientType.BCC,
wrapAddress(mailInfo.getMsAddress()))
mailMessage.setSubject(mailInfo.getSubject())// 设置邮件消息的主题
mailMessage.setSentDate(new Date())// 设置邮件消息发送的时间
// mailMessage.setText(mailInfo.getContent())//设置邮件消息的主要内容
// MimeMultipart类是一个容器类,包含MimeBodyPart类型的对象
Multipart mainPart = new MimeMultipart()
MimeBodyPart messageBodyPart = new MimeBodyPart()// 创建一个包含附件内容的MimeBodyPart
// 设置HTML内容
messageBodyPart.setContent(mailInfo.getContent(),
"text/html charset=" + encode)
mainPart.addBodyPart(messageBodyPart)
// 存在附件
String[] filePaths = mailInfo.getAttachFileNames()
if (filePaths != null && filePaths.length > 0) {
for (String filePath : filePaths) {
messageBodyPart = new MimeBodyPart()
File file = new File(filePath)
if (file.exists()) {// 附件存在磁盘中
FileDataSource fds = new FileDataSource(file)// 得到数据源
messageBodyPart
.setDataHandler(new DataHandler(fds))// 得到附件本身并至入BodyPart
messageBodyPart.setFileName("=?" + encode + "?B?"
+ file.getName())// 得到文件名同样至入BodyPart
mainPart.addBodyPart(messageBodyPart)
}
}
}
// 将MimeMultipart对象设置为邮件内容
mailMessage.setContent(mainPart)
Transport.send(mailMessage)// 发送邮件
return true
} catch (Exception e) {
e.printStackTrace()
try {
java.util.concurrent.TimeUnit.SECONDS.sleep(5)
} catch (Exception e2) {
e2.printStackTrace()
}
}
}
return false
}
/**
* 将string[]包装成EmailAddress
* @param mailInfo
* @return
* @throws AddressException
*/
private static Address [] wrapAddress(String[] adds) throws AddressException {
// String[] adds = mailInfo.getToAddress()
if(adds == null || adds.length == 0){
return null
}
Address []to = new Address[adds.length]
for(int i = 0i<adds.lengthi++){
to[i]=new InternetAddress(adds[i])
}
return to
}
/**
* 以HTML格式发送邮件
*
* @param mailInfo
* @return
*/
public static boolean sendHtmlMail(MailInfo mailInfo) {
for (int i = 0 i < 3 i++) {
// 判断是否需要身份认证
MyAuthenticator authenticator = null
Properties properties = mailInfo.getProperties()
if (mailInfo.isValidate()) {
// 如果需要身份认证,则创建一个密码验证器
authenticator = new MyAuthenticator(mailInfo.getUsername(),
mailInfo.getPassword())
}
// 根据邮件会话属性和密码验证器构造一个发送邮件的session
Session sendMailSession = Session.getDefaultInstance(properties,
authenticator)
if (mailInfo.isDebug()) {
sendMailSession.setDebug(true)
}
try {
Message mailMessage = new MimeMessage(sendMailSession)// 根据session创建一个邮件消息
Address from = new InternetAddress(mailInfo.getFromAddress())// 创建邮件发送者地址
mailMessage.setFrom(from)// 设置邮件消息的发送者
// Address to = new InternetAddress(mailInfo.getToAddress())//
// 创建邮件的接收者地址
// mailMessage.setRecipient(Message.RecipientType.TO, to)//
// 设置邮件消息的接收者
mailMessage.setRecipients(Message.RecipientType.TO,
wrapAddress(mailInfo.getToAddress()))
// InternetAddress ms = new
// InternetAddress(mailInfo.getMsAddress())
// mailMessage.setRecipient(Message.RecipientType.BCC, ms) //
// 密送人
mailMessage.setRecipients(Message.RecipientType.BCC,
wrapAddress(mailInfo.getMsAddress()))
mailMessage.setSubject(mailInfo.getSubject())// 设置邮件消息的主题
mailMessage.setSentDate(new Date())// 设置邮件消息发送的时间
// MimeMultipart类是一个容器类,包含MimeBodyPart类型的对象
Multipart mainPart = new MimeMultipart()
MimeBodyPart messageBodyPart = new MimeBodyPart()// 创建一个包含HTML内容的MimeBodyPart
// 设置HTML内容
messageBodyPart.setContent(mailInfo.getContent(),
"text/html charset=" + encode)
mainPart.addBodyPart(messageBodyPart)
// 存在附件
String[] filePaths = mailInfo.getAttachFileNames()
if (filePaths != null && filePaths.length > 0) {
sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder()
for (String filePath : filePaths) {
messageBodyPart = new MimeBodyPart()
File file = new File(filePath)
if (file.exists()) {// 附件存在磁盘中
FileDataSource fds = new FileDataSource(file)// 得到数据源
messageBodyPart
.setDataHandler(new DataHandler(fds))// 得到附件本身并至入BodyPart
messageBodyPart.setFileName("=?" + encode + "?B?"
+ enc.encode(EmailFileNameConvert.changeFileName(file.getName()).getBytes())
+ "?=")// 得到文件名同样至入BodyPart
mainPart.addBodyPart(messageBodyPart)
}
}
}
// 将MimeMultipart对象设置为邮件内容
mailMessage.setContent(mainPart)
Transport.send(mailMessage)// 发送邮件
return true
} catch (Exception e) {
e.printStackTrace()
try {
java.util.concurrent.TimeUnit.SECONDS.sleep(5)
} catch (Exception e2) {
e2.printStackTrace()
}
}
}
return false
}
}
/**
* 封装邮件的基本信息
*
* @author Sglee
*
*/
public class MailInfo implements Serializable{
/**
*
*/
private static final long serialVersionUID = -3937199642590071261L
private String mailServerHost// 服务器ip
private String mailServerPort// 端口
private long timeout// 超时时间
private String fromAddress// 发送者的邮件地址
private String[] toAddress// 邮件接收者地址
private String[] msAddress// 密送地址
private String username// 登录邮件发送服务器的用户名
private String password// 登录邮件发送服务器的密码
private boolean validate = false// 是否需要身份验证
private String subject// 邮件主题
private String content// 邮件内容
private String[] attachFileNames// 附件的文件地址
private boolean debug// 调试模式
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")
p.put("mail.smtp.timeout", this.timeout)
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 String getFromAddress() {
return fromAddress
}
public void setFromAddress(String fromAddress) {
this.fromAddress = fromAddress
}
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 getPassword() {
return password
}
public void setPassword(String password) {
this.password = password
}
public boolean isValidate() {
return validate
}
public void setValidate(boolean validate) {
this.validate = validate
}
public String getSubject() {
return subject
}
public void setSubject(String subject) {
this.subject = subject
}
public String getContent() {
return content
}
public void setContent(String content) {
this.content = content
}
public String[] getAttachFileNames() {
return attachFileNames
}
public void setAttachFileNames(String[] attachFileNames) {
this.attachFileNames = attachFileNames
}
public void setMsAddress(String[] msAddress) {
this.msAddress = msAddress
}
public String[] getMsAddress() {
return msAddress
}
public void setDebug(boolean debug) {
this.debug = debug
}
public boolean isDebug() {
return debug
}
public void setTimeout(long timeout) {
this.timeout = timeout
}
public long getTimeout() {
return timeout
}
}
public class MyAuthenticator extends Authenticator {
private String username = null
private 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)
}
}
注意一下:
Myeclipse自带的JavaEE5.jar和java mail会发生冲突
找到ME下的javeee包
D:\MyEclipse 8.5\Common\plugins\com.genuitec.eclipse.j2eedt.core_8.5.0.me201003231033\data\libraryset\EE_5\javaee.jar
用rar等解压工具解开javaee.jar,删除里面的javax\mail文件夹(可以先备份javaee.jar)
也即,以后都不能使用javaee.jar里面的邮件api发送邮件了.
package com.victorimport java.io.File
import java.io.IOException
import java.io.InputStream
import java.util.Properties
import javax.activation.DataHandler
import javax.activation.DataSource
import javax.activation.FileDataSource
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
import javax.mail.internet.MimeUtility
public class JavaMailWithAttachment {
private MimeMessage message
private Session session
private Transport transport
private String mailHost = ""
private String sender_username = ""
private String sender_password = ""
private Properties properties = new Properties()
/*
* 初始化方法
*/
public JavaMailWithAttachment(boolean debug) {
InputStream in = 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 (IOException e) {
e.printStackTrace()
}
session = Session.getInstance(properties)
session.setDebug(debug)//开启后有调试信息
message = new MimeMessage(session)
}
/**
* 发送邮件
*
* @param subject
* 邮件主题
* @param sendHtml
* 邮件内容
* @param receiveUser
* 收件人地址
* @param attachment
* 附件
*/
public void doSendHtmlEmail(String subject, String sendHtml, String receiveUser, File attachment) {
try {
// 发件人
InternetAddress from = new InternetAddress(sender_username)
message.setFrom(from)
// 收件人
InternetAddress to = new InternetAddress(receiveUser)
message.setRecipient(Message.RecipientType.TO, to)
// 邮件主题
message.setSubject(subject)
// 向multipart对象中添加邮件的各个部分内容,包括文本内容和附件
Multipart multipart = new MimeMultipart()
// 添加邮件正文
BodyPart contentPart = new MimeBodyPart()
contentPart.setContent(sendHtml, "text/htmlcharset=UTF-8")
multipart.addBodyPart(contentPart)
// 添加附件的内容
if (attachment != null) {
BodyPart attachmentBodyPart = new MimeBodyPart()
DataSource source = new FileDataSource(attachment)
attachmentBodyPart.setDataHandler(new DataHandler(source))
// 网上流传的解决文件名乱码的方法,其实用MimeUtility.encodeWord就可以很方便的搞定
// 这里很重要,通过下面的Base64编码的转换可以保证你的中文附件标题名在发送时不会变成乱码
//sun.misc.BASE64Encoder enc = new sun.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("send success!")
} catch (Exception e) {
e.printStackTrace()
} finally {
if (transport != null) {
try {
transport.close()
} catch (MessagingException e) {
e.printStackTrace()
}
}
}
}
public static void main(String[] args) {
JavaMailWithAttachment se = new JavaMailWithAttachment(true)
System.out.println(se)
File affix = new File("E:\\测试-test.txt")
// File affix =null
se.doSendHtmlEmail("##", "###", "####@##.com", affix)//
}
}
注意点:1 jar可能有冲突,如果是demo可以直接应用mail.jar
如果是一个工程则要替换javaEE中的mail.jar包
2 关于properties配置文件的地址问题
Class.getResourceAsStream(String path) : path 不以’/'开头时默认是从此类所在的包下取资源,以’/'开头则是从
ClassPath根下获取。其只是通过path构造一个绝对路径,最终还是由ClassLoader获取资源。
欢迎分享,转载请注明来源:夏雨云
评论列表(0条)