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格式
} }

java mail邮件发送(带附件) 支持SSL的更多相关文章

  1. System.Net.Mail邮件发送抄送附件(多个)

    /// <summary> /// 邮件发送抄送附件 /// </summary> /// <param name="mailTo">收件人(可 ...

  2. 161013、java实现邮件群发带附件

    要完成Java群发邮件功能,首先须加入mail.jar和activation.jar这两个包 下面是邮件的例子: import java.io.File; import java.util.Prope ...

  3. Java Mail 邮件发送简单封装

    上一篇文章我们用写了一个Java Mail 的Demo,相信你已经可以用那个例子来发送邮件了.但是Demo 有很多的问题. 首先每次发送需要配置的东西很多,包括发件人的邮箱和密码.smtp服务器和SM ...

  4. Java Mail邮件发送的简单实现

    1.什么是java mail JAVA MAIL是利用现有的邮件账户发送邮件的工具,通过JAVA Mail的操控,让程序自动的使用设置的邮箱发送邮件. 这一机制被广泛的用在注册激活和垃圾邮件的发送等方 ...

  5. Spring的javaMail邮件发送(带附件)

    项目中经常用到邮件功能,在这里简单的做一下笔记,方便日后温习. 首先需要在配置文件jdbc.properties添加: #------------ Mail ------------ mail.smt ...

  6. Java Mail 邮件发送Demo

    上周公司的项目要求开发邮件发送功能.自己在网上跟着教程边学边做了一下午,现在基本开发完成了.由于一个同事也想看下该怎么写,顺便学习下.所以我就写成了一遍教程,顺便巩固下邮件发送里面的内容. Demo ...

  7. UiPath: Send SMTP Mail Message 发送带附件的邮件

    Tips:关于Hotmail的server和port的获取方式,请参考以下链接 https://support.office.com/en-us/article/Server-settings-you ...

  8. [PHP]使用PHPMailer发送带附件并支持HTML内容的邮件

    来源:http://www.helloweba.com/view-blog-205.html PHPMailer是一个封装好的PHP邮件发送类,支持发送HTML内容的电子邮件,以及可以添加附件发送,并 ...

  9. java发送带附件的邮件

    /** * java发送带附件的邮件 * 周枫 * 2013.8.10 */ package com.dsideal.Util; import javax.mail.*; import javax.m ...

随机推荐

  1. 让VMware ESXi虚拟交换机支持VLAN

    眼下虚拟化应用比較广泛,通常情况下.一台物理主机在安装VMware ESXi或Hyper-V虚拟机软件后.能够在一台物理主机上创建多个虚拟机,而且创建的每一个虚拟机能够像原来的物理一样对外提供服务,这 ...

  2. [ACM] POJ 2154 Color (Polya计数优化,欧拉函数)

    Color Time Limit: 2000MS   Memory Limit: 65536K Total Submissions: 7630   Accepted: 2507 Description ...

  3. XML系统学习

    参考:W3School XML基本概念 1.XML是eXtensible Markup Language,使用DTD(Document Type Definition)来描述数据,主要是为传输和存储数 ...

  4. HDU 2054 A==B? 大数

    Problem Description Give you two numbers A and B, if A is equal to B, you should print "YES&quo ...

  5. Spark SQL with Hive

    前一篇文章是Spark SQL的入门篇Spark SQL初探,介绍了一些基础知识和API,可是离我们的日常使用还似乎差了一步之遥. 终结Shark的利用有2个: 1.和Spark程序的集成有诸多限制 ...

  6. Xcode6 引入第三方静态库project的方法

    首先.介绍一下把在当前project中引入其它依赖project的方法: 第一:把其它项目project加入到现有project做法: 定义: FPro 现有project == 父project C ...

  7. 前端学习笔记-CSS

  8. Android WebView访问网站携带登录认证Cookies和动态自定义的cookies

    最近项目几个页面要复用微信程序的网页.但是需要调用微网站登录接口,返回Cookies,webview访问需要的网页的时候携带. 并且还需要几个其他的动态改变的cookie,目的是根据这几个动态自定义c ...

  9. Python学习——BeautifulSoup篇

    BeautifulSoup     Beautiful Soup 是一个可以从HTML或XML文件中提取数据的Python库.它能够通过你喜欢的转换器实现惯用的文档导航,查找,修改文档的方式.Beau ...

  10. SQL SERVER中的sys.objects和sysobjects的区别

    这三个视图都是存在于SQL Server的每个数据库中.在SQL Server 2000中,它们都是系统表,而不是视图. 关于两个版本中系统表和系统的视图的对应关系,参考:http://technet ...