`

java发送邮件,Authenticator,Session,Message,Multipart,BodyPart

阅读更多

使用java实现发送邮件功能,主要用到了Authenticator,Session,Message,Multipart,BodyPart。

Authenticator:抽象类,继承该类要实现getPasswordAuthentication方法,该方法主要是获取邮箱账户密码,用于用户验证。

Session:根据Properties属性,和用户验证信息创建MimeMessage;

Message:即MimeMessage,用户填写邮件的一些信息,如发送者,接收者,主题,内容,附件等;

Multipart:容器类,用于装作封装了邮件正文内容和附件的BodyPart;

BodyPart:封装邮件正文和附件及编写附件名称,有一点需要注意,如果邮件中有附件,一定要先添加附件后添加邮件正文,如果顺序颠倒,你编写的邮件正文内容会被附件覆盖掉;

以下为正式代码:

package cn.tongmap.global;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
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 Mail extends Authenticator{
	//账号
	private static String ACCOUNT_NUMBER;
	//密码
	private static String SECURITY_CODE;
	//邮箱主机
	private static String MAIL_SMTP_HOST;
	//邮箱端口
	private static int MAIL_SMTP_PORT;
	//是否验证
	private static boolean MAIL_SMTP_AUTH;
	
	static {
		Properties pro = null;
		try {
			pro = new Properties();
			pro.load(Mail.class.getResourceAsStream("/mail.properties"));
			//人流量数据SFTP服务器信息
			ACCOUNT_NUMBER = pro.getProperty("ACCOUNT_NUMBER").trim();
			SECURITY_CODE = pro.getProperty("SECURITY_CODE").trim();
			MAIL_SMTP_HOST = pro.getProperty("MAIL_SMTP_HOST").trim();
			MAIL_SMTP_PORT = Integer.parseInt(pro.getProperty("MAIL_SMTP_PORT").trim());
			MAIL_SMTP_AUTH = Boolean.parseBoolean(pro.getProperty("MAIL_SMTP_AUTH").trim());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	//邮件主题
	private String subject;
	//邮件内容,可以使用html
	private String content;
	//附件源
	private String fileDataSource;
	//邮件接收者
	private List<String> recipients;
	
	public Mail() {
	}

	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 getFileDataSource() {
		return fileDataSource;
	}

	public void setFileDataSource(String fileDataSource) {
		this.fileDataSource = fileDataSource;
	}

	public List<String> getRecipients() {
		return recipients;
	}

	public void setRecipients(List<String> recipients) {
		this.recipients = recipients;
	}
	/**
	 * 此方法一定要实现,否侧会连接出错,因为要进行用户名密码验证
	 */
	protected PasswordAuthentication getPasswordAuthentication() {
		return new PasswordAuthentication(ACCOUNT_NUMBER, SECURITY_CODE);
	}

	/**
	 * 邮件发送,在实例化对象的时候会需要填写一些发送邮件必要参数
	 * 在发送邮件时不需要任何参数
	 * @return 返回内容为字符串,用于提示邮件发送结果或错误提示
	 * @throws Exception
	 */
	public String send() throws Exception {
		if(null == recipients || recipients.size() == 0) {
			return "请填写邮件接收者!";
		}
		if(null == subject || "".equals(subject)) {
			return "请填写邮寄主题!";
		}
		if(null == content || "".equals(content)) {
			return "请填写邮寄内容!";
		}
		Authenticator auth = new Mail();
		Properties pro = new Properties();
		pro.put("mail.smtp.host", MAIL_SMTP_HOST);
		pro.put("mail.smtp.port", MAIL_SMTP_PORT);
		pro.put("mail.smtp.auth", MAIL_SMTP_AUTH);
		Session sendMailSession = Session.getDefaultInstance(pro, auth);
		// 根据session创建一个邮件消息
		Message mailMessage = new MimeMessage(sendMailSession);
		// 创建邮件发送者地址
		Address from = new InternetAddress(ACCOUNT_NUMBER);
		// 设置邮件消息的发送者
		mailMessage.setFrom(from);
		// 创建邮件的接收者地址,并设置到邮件消息中
		Address[] tos = new Address[recipients.size()];
		for (int i = 0; i < tos.length; i++) {
			tos[i] = new InternetAddress(recipients.get(i));
		}
		// Message.RecipientType.TO属性表示接收者的类型为TO
		mailMessage.setRecipients(Message.RecipientType.TO, tos);
		// 设置邮件消息的主题
		mailMessage.setSubject(subject);
		// 设置邮件消息发送的时间
		mailMessage.setSentDate(new Date());
		// MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象
		Multipart mainPart = new MimeMultipart();
		// 创建一个包含HTML内容的MimeBodyPart
		BodyPart html = new MimeBodyPart();
		//是否存在附件
		if(null != fileDataSource && !"".equals(fileDataSource)) {
			File file = new File(fileDataSource);
			if(file.exists()) {
				FileDataSource data = new FileDataSource(file);
				html.setDataHandler(new DataHandler(data));
				//避免文件名中文乱码
				String name = MimeUtility.encodeWord(file.getName());
				html.setFileName(name);
			} else {
				return "邮件中存在无效附件!";
			}
		}
		// 设置HTML内容,设置内容步骤要放在设置附件之后,以免内容被覆盖
		html.setContent(content, "text/html; charset=utf-8");
		mainPart.addBodyPart(html);
		// 将MiniMultipart对象设置为邮件内容
		mailMessage.setContent(mainPart);
		// 发送邮件
		Transport.send(mailMessage);
		return "邮件发送成功!";
	}
}

 其中mail.properties为邮件配置文件,单独放出来便于管理:

ACCOUNT_NUMBER = You Email@163.com
SECURITY_CODE = You Email Password
MAIL_SMTP_HOST = smtp.163.com
MAIL_SMTP_PORT = 25
MAIL_SMTP_AUTH =true

 

  • mail-1.4.3.jar (451.3 KB)
  • 描述: 发送邮件所需的jar包
  • 下载次数: 0
分享到:
评论

相关推荐

    Java邮件发送

    3. * 发送邮件需要使用的基本信息 4. */ 5. import java.util.Properties; 6. public class MailSenderInfo { 7. // 发送邮件的服务器的IP和端口 8. private String mailServerHost; 9. private String ...

    java自动发邮件

    if (k &gt; time) { //超过设定时间间隔开始发送邮件 sendData(); lastTime = new Date().getTime(); } try { Thread.sleep(100); } catch (Exception e) {} } } public void stop() { flag = false; } ...

    javamail发送邮件

    2.发送邮件需要的几个重要类Session ,Message,Transport 3.Session对象可以通过Session的getInstance(java.util.Properties props) 或getInstance(java.util.Properties props, Authenticator authenticator) ...

    java邮件引擎调用

    Message message = new MimeMessage(session); message.setRecipients(Message.RecipientType.TO, InternetAddress .parse("old5th@gmail.com")); message.setSubject("Testing Subject"); message...

    GoogleAuthenticator-java实现.zip

    java服务端实现谷歌动态密码验证,包含二唯码字段,阿里身份宝的下载路径为:..._used=&channel=WEB&fdh=no&id_file=012200c6-9b29-11e6-95c0-00163ed833e7&instance=softonic_en&type=PROGRAM&url=...

    发送邮件的Java代码

    // 所发送邮件的标题 // String from = "401171674@qq.com";// 从那里发送 // String sendTo[] = {"19811401@qq.com"};// 发送到那里 // // 邮件的文本内容,可以包含html标记则显示为html页面 // String content = ...

    07_传智播客张孝祥java邮件开发_使用Authenticator和send静态方法.rar

    07_传智播客张孝祥java邮件开发_使用Authenticator和send静态方法.rar

    Java邮件开发Fundamentals of the JavaMail API

    Looking to incorporate mail facilities into your platform-independent Java solutions? Look no further than the JavaMail API, which offers a protocol-independent model for working with IMAP, POP, ...

    邮件发送代码

    * 发送邮件方法 * @param to 收件人 * @param code 激活码 */ public static void sendMail(String to,String code){ /** * 1.获得一个Seesion对象 * 2.创建邮件对象(Message) * 3.发送邮件...

    复杂邮件程序完整Java源码,支持添加附件,图片,HTML格式文本,支持远程WebService调用

    * sendMail 发送邮件函数 * * @param sender 是String类型,邮件发送者信息 * @param password 是String类型,邮件发送者密码 * @param addressee 是String类型,邮件接收者信息 * @param subject 是String类型,...

    java使用google身份验证器实现动态口令验证的示例

    本篇文章主要介绍了java使用google身份验证器实现动态口令验证的示例,具有一定的参考价值,有兴趣的可以了解一下

    java_发送email_web所需要加的jar包

    在web开发中,使用java发送email,需要加入两个jar包。在普通的java程序中可能不需要加入。 但在web中没加入会抛 javax.mail.Authenticator not Founder或java.lang.reflect.InvocationTargetException

    javaemail源码-java-mail:通过使用开源JavaMailAPI,我在教师的帮助下构建了一个程序,以通过Java代码发送电子邮件

    电子邮件Java 软件包gmailemail; 导入java.util.Properties; 导入java.util.logging.Level; 导入java.util.logging.Logger; 导入javax.mail.Session; 导入javax.mail.PasswordAuthentication; 导入javax.mail....

    java笔试题算法-GoogleAuth:GoogleAuthenticator服务器端代码

    java笔试题算法 自述文件 GoogleAuth 是一个 Java 服务器库,它实现了 中指定的基于时间的一次性密码(TOTP) 算法。 此实现借用了 ,其 C 代码已用作参考,并且是根据 Enrico M. Crisostomo 发布的代码创建的。 这个...

    Java Mail基本的发送邮件例子

    首先需要导入jar包,mail-1.4.2.jar,然后给出简单的java mail发送邮件的代码,SimpleSendMailDemo.java  SimpleSendMailDemo.java   package com.steven.mail; import java.util.Properties; ...

    googleAuthenticator windows版

    googleAuthenticator windows版 googleAuth winAuth win10版 谷歌双向认证win版程序

    从Java走向Java+EE+.rar

    15.3.2 编写发送邮件的实例 223 15.3.3 编写接收邮件的实例 235 15.4 小结 241 第16章 基于良好设计模式的Spring 243 16.1 Spring简介 243 16.2 实例——用Spring来打招呼 246 16.3 小结 248 第17章 ...

    googleAuthenticator windows版1.5版

    googleauth 动态密码win版 googleauthenticator windows版 winauth win10版

    简易实用的JavaMail邮箱程序

    // 发送邮件 } } /** * ValidateAuther 邮件验证类,验证邮件发送者信息 */ class ValidateAuther extends Authenticator { /** 邮件发送者 */ private String sender; /** 邮件接受者 */ private String...

Global site tag (gtag.js) - Google Analytics