您的位置:首页 > 编程语言 > Java开发

java mail邮件发送(带附件) 支持SSL

2014-11-06 18:47 375 查看
java mail邮件发送(带附件)有三个类

MailSenderInfo.java

package mail;

import java.util.Properties;
import java.util.Vector;
public class MailSenderInfo {
// 发送邮件的server的IP和端口
private String mailServerHost;
private String mailServerPort = "25";
// 邮件发送者的地址
private String fromAddress;
// 邮件接收者的地址
private String toAddress;
// 登陆邮件发送server的username与password
private String userName;
private String password;
// 是否须要身份验证
private boolean validate = false;
// 是否启用ssl
private boolean validateSSL = false;
// 邮件主题
private String subject;
// 邮件的文本内容
private String content;
// 邮件附件的文件名称
private Vector 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 Vector getAttachFileNames() {
return attachFileNames;
}
public void setAttachFileNames(Vector attachFileNames) {
this.attachFileNames = attachFileNames;
}
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;
}
public boolean isValidateSSL() {
return validateSSL;
}
public void setValidateSSL(boolean validateSSL) {
this.validateSSL = validateSSL;
}
}
MailAuthenticator.java

package mail;

import javax.mail.*;

public class MailAuthenticator extends Authenticator {

private String userName;
private String password;

public MailAuthenticator() {
}

public MailAuthenticator(String username, String password) {
this.userName = username;
this.password = password;
}

protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
}


SimpleMailSender.java

package mail;

import java.util.Date;
import java.util.Enumeration;
import java.util.Properties;
import java.util.Vector;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
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;
import javax.mail.internet.MimeUtility;

/**
* 简单邮件(带附件的邮件)发送器
*/
public class SimpleMailSender {

/**
* 以html发送邮件(带附件)
*
* @param mailInfo
*            待发送的邮件的信息
*/
public boolean sendHtmlAndAffixMail(MailSenderInfo mailInfo) {
// 推断是否须要身份认证
MailAuthenticator authenticator = null;
Properties pro = mailInfo.getProperties();
if(mailInfo.isValidateSSL()){
pro.put("mail.smtp.starttls.enable","true");
pro.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
}
// 假设须要身份认证,则创建一个password验证器
if (mailInfo.isValidate()) {
authenticator = new MailAuthenticator(mailInfo.getUserName(),
mailInfo.getPassword());
}
// 依据邮件会话属性和password验证器构造一个发送邮件的session
Session session = Session.getDefaultInstance(pro, authenticator);
try {
MimeMessage msg = new MimeMessage(session); // 构造MimeMessage 并设定主要的值
// MimeMessage msg = new MimeMessage();
msg.setFrom(new InternetAddress(mailInfo.getFromAddress()));
// msg.addRecipients(Message.RecipientType.TO, address);
// //这个仅仅能是给一个人发送email
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(mailInfo.getToAddress()));
msg.setSubject(MimeUtility.encodeText(mailInfo.getSubject()));
Multipart mp = new MimeMultipart();// 构造Multipart
MimeBodyPart mbpContent = new MimeBodyPart();// 向Multipart加入正文
mbpContent.setContent(mailInfo.getContent(),
"text/html;charset=GB2312");
mp.addBodyPart(mbpContent);// 向MimeMessage加入(Multipart代表正文)
Vector file = mailInfo.getAttachFileNames();
Enumeration efile = file.elements();// 向Multipart加入附件
while (efile.hasMoreElements()) {
MimeBodyPart mbpFile = new MimeBodyPart();
String filename = efile.nextElement().toString();
System.out.println(filename.toLowerCase());
FileDataSource fds = new FileDataSource(filename);
mbpFile.setDataHandler(new DataHandler(fds));
System.out.println(fds.getName());
mbpFile.setFileName(MimeUtility.encodeText(fds.getName()));
// 向MimeMessage加入(Multipart代表附件)
mp.addBodyPart(mbpFile);
}
file.removeAllElements();
// 向Multipart加入MimeMessage
msg.setContent(mp);
msg.setSentDate(new Date());
msg.saveChanges();
// 发送邮件
Transport transport = session.getTransport("smtp");
transport.connect(mailInfo.getMailServerHost(), mailInfo
.getUserName(), mailInfo.getPassword());
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
} catch (Exception mex) {
mex.printStackTrace();
return false;
}
return true;

}

}
測试类

package mail;

import java.util.Vector;

public class MailTest {

/**
* @param args
*/
public static void main(String[] args) {
//这个类主要是设置邮件
MailSenderInfo mailInfo = new MailSenderInfo();
mailInfo.setMailServerHost(host);
mailInfo.setMailServerPort("465");
mailInfo.setValidate(true);
mailInfo.setValidateSSL(true);
mailInfo.setUserName("username");
mailInfo.setPassword("pwd");//您的邮箱password
mailInfo.setFromAddress("address");
mailInfo.setToAddress("XXXXX@sina.cn");
mailInfo.setSubject("设置邮箱标题");
mailInfo.setContent("今天应该是魅族粉的狂欢日!"+
"今天魅族在北京正式公布MX4,魅族MX4採用5.36寸1920×1152分辨率屏幕(PPI418),搭载联发科八核处理器,提供2070万像素摄像头,配备3100mAh电池,执行全新的Flyme 4.0系统,支持移动与联通网络双4G,安兔兔跑分46124分,提供深灰色、纯白色及土豪金版本号,16G版售价1799元,32G版售价1999元。");
//这个类主要来发送邮件
Vector fileNames = new Vector();
fileNames.add("D:\\delete\\周报表20140903103213.xls");
fileNames.add("D:\\delete\\复件 周报表20140903103213.xls");
fileNames.add("D:\\delete\\复件 (2) 周报表20140903103213.xls");
mailInfo.setAttachFileNames(fileNames);
SimpleMailSender sms = new SimpleMailSender();
// sms.sendTextMail(mailInfo);//发送文体格式
sms.sendHtmlAndAffixMail(mailInfo);//发送html格式
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: