java mail邮件发送(带附件)

java mail邮件发送(带附件)有三个类

MailSenderInfo.java

package mail;

import java.util.Properties;
import java.util.Vector;
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;
    // 是否启用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 {
	/**
	 * 以文本格式发送邮件
	 *
	 * @param mailInfo
	 *            待发送的邮件的信息
	 */
	public boolean sendTextMail(MailSenderInfo mailInfo) {
		// 判断是否需要身份认证
		MailAuthenticator authenticator = null;
		Properties pro = mailInfo.getProperties();
		if (mailInfo.isValidate()) {
			// 如果需要身份认证,则创建一个密码验证器
			authenticator = new MailAuthenticator(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) {
		// 判断是否需要身份认证
		MailAuthenticator authenticator = null;
		Properties pro = mailInfo.getProperties();
		// 如果需要身份认证,则创建一个密码验证器
		if (mailInfo.isValidate()) {
			authenticator = new MailAuthenticator(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;
	}

	/**
	 * 以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");
		}
		// 如果需要身份认证,则创建一个密码验证器
		if (mailInfo.isValidate()) {
			authenticator = new MailAuthenticator(mailInfo.getUserName(),
					mailInfo.getPassword());
		}
		// 根据邮件会话属性和密码验证器构造一个发送邮件的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("smtp.XXXXXX.com");
	      mailInfo.setMailServerPort("465");
	      mailInfo.setValidate(true);
	      mailInfo.setValidateSSL(true);
	      mailInfo.setUserName("[email protected]<span style="font-family: Arial, Helvetica, sans-serif;">XXXXXX</span><span style="font-family: Arial, Helvetica, sans-serif;">.com");    </span>
	      mailInfo.setPassword(pwd);//您的邮箱密码
	      mailInfo.setFromAddress(<span style="font-family: Arial, Helvetica, sans-serif;">"[email protected]</span><span style="font-family: Arial, Helvetica, sans-serif;">XXXXXX</span><span style="font-family: Arial, Helvetica, sans-serif;">.com"</span><span style="font-family: Arial, Helvetica, sans-serif;">);    </span>
	      mailInfo.setToAddress("[email protected]");
	      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格式
	}

}
时间: 2024-09-30 04:52:52

java mail邮件发送(带附件)的相关文章

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

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"; // 邮件发送者的地址 pr

java mail 邮件发送实例【搬】

说明:转自国外博客:欢迎查阅原作 该实例较新,简明易懂,值得新手借鉴 以gmail为例,注意: 1.通过TLS方式发送 1 package com.mkyong.common; 2 3 import java.util.Properties; 4 5 import javax.mail.Message; 6 import javax.mail.MessagingException; 7 import javax.mail.PasswordAuthentication; 8 import java

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

要完成Java群发邮件功能,首先须加入mail.jar和activation.jar这两个包 下面是邮件的例子: import java.io.File; import java.util.Properties; import java.util.Vector; import javax.mail.internet.MimeUtility; /** * 发送邮件的信息类 * @author 仇志鹏 * @version 2016.10.19 * */ public class MailSende

Java Mail邮件发送的简单实现

1.什么是java mail JAVA MAIL是利用现有的邮件账户发送邮件的工具,通过JAVA Mail的操控,让程序自动的使用设置的邮箱发送邮件. 这一机制被广泛的用在注册激活和垃圾邮件的发送等方面. 2.邮件发送的大致过程 1.构建一个继承自javax.mail.Authenticator的具体类,并重写里面的getPasswordAuthentication()方法.此类是用作登录校验的,以确保你对该邮箱有发送邮件的权利. 2.构建一个properties文件,该文件中存放SMTP服务器

python之简单邮件发送(带附件、图片)

#!/usr/bin/env python #coding: utf-8 by guozheng_li #该脚本加入了文本.图片以及附件功能,日常运维跑的脚本基本也就这三样够用了.可以发送给多人,只要添加相应的mailto_list即可,再加入该说明前验证是正常的 import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.im

Android上发送带附件的邮件

准备工作-下载最新版本的JMail https://java.net/projects/javamail/pages/Home#Download_JavaMail_1.5.2_Release http://www.oracle.com/technetwork/java/javase/downloads/index-135046.html 在android上发送邮件方式: 第一种:借助GMail APP客户端,缺点是必须使用GMail帐号,有点是比较方便 不需要写很多代码,但是不是很灵活. 第二种

(转)用javamail发送带附件的邮件

本文转载自:http://redleaf.iteye.com/blog/78217 mail.java 代码 package mail; import java.util.* ; import java.io.* ; import javax.mail.* ; import javax.mail.internet.* ; import javax.activation.* ; public class Mail { //定义发件人.收件人.SMTP服务器.用户名.密码.主题.内容等 privat

利用springframework+javax.mail发邮件(普通邮件、带附件邮件、HTML格式邮件)

Spring提供了发送电子邮件的支持,可以发送普通邮件.带附件邮件.HTML格式邮件,甚至还可以使用Velocity模板定制化邮件内容. 一.引入相关的库 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 <!-- spring核心库 -->         <dependency>             <groupId>org.springframework<

Python2.7 smtplib发送带附件邮件报错STARTTLS解决方法

最近在SIOMP系统中添加一项功能时,即自动发送带附件邮件到指定邮箱时,发现在发送时报错:错误信息:STARTTLS extension not supported by server.很是奇怪,但发送无附件邮件时,可以正常发送,且不报错,前期以为是代码存在问题,如果调出对应的错误信息反馈,似乎和代码没有什么关系: 详细代码如下所示: # -*- coding: utf-8 -*- import email from email.mime.text import MIMEText from em