Spring JavaMail发送邮件
JavaMail的介绍
JavaMail,顾名思义,提供给开发者处理电子邮件相关的编程接口。它是Sun发布的用来处理email的API。它可以方便地执行一些常用的邮件传输。
虽然JavaMail是Sun的API之一,但它目前还没有被加在标准的java开发工具包中(Java Development Kit),这就意味着你在使用前必须另外下载JavaMail文件。除此以外,你还需要有Sun的JavaBeans Activation Framework (JAF)。JavaBeans Activation Framework的运行很复杂,在这里简单的说就是JavaMail的运行必须得依赖于它的支持。在Windows 2000下使用需要指定这些文件的路径,在其它的操作系统上也类似。
1.邮件协议
主要包括:
SMTP协议:Simple Mail Transfer Protocol,即简单邮件传输协议,用于发送电子邮件
POP3协议:Post Office Protocol 3,即邮局协议的第三个版本,用于接收邮件
IMAP协议:Internet Message Access Protocol,即互联网消息访问协议,是POP3的替代协议
2.搭建James邮件服务器
James是Apache的一个开源项目,纯Java实现
搭建James服务器
1)下载apache-james-2.3.2.zip解压
2)运行bin目录下的run.bat即可启动服务器
3) 通过apps\james\SAR-INF\config.xml配置服务器
一定注意:先到bin下run一道 放如非中文目录 得再控制面板开启Telnet客户端
Telnet localhost 4555
3.安装OutLook[邮件客户端]
产品秘钥:PQDV9-GPDV4-CRM4D-PHDTH-4M2MT
创建用户账号
一、使用telnet连接James的Remote Administration Tool
二、以管理员身份登录
三、使用adduser命令添加用户
4.配置outlook邮件客户端
为了方便查看,可以配置Microsoft Outlook邮件客户端,保证James邮件服务器是启动状态,启动Microsoft Outlook.
选择“工具”->“选项”,打开“选项”面板。选择“邮件设置”并点击“电子邮件账户”,打开“账号设置”面板。在“电子邮件”选项卡下新建邮件账户
5.案例[搭建James邮件服务器]
需求说明:
在本机搭建James邮件服务器,自定义服务器的名称。
创建两个测试用户。
在Microsoft Outlook中配置其中一个测试用户为Outlook邮件账户
6.使用JavaMail发送电子邮件(案例)
需求:
使用JavaMail技术,实现从A账户给B账户发送一封电子邮件,标题为“会议通知”,邮件内容为“XX你好!请于明天下午16:00 准时到B01会议室召开技术讨论会。”通过Outlook 客户端查看邮件程序发送的邮件是否发送成功
关键代码:
创建一个类EmailAuthenticator并继承自Authenticator,并植入用户名和密码
package cn.mail; import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication; public class EmailAuthenticator extends Authenticator {
private String username; private String userpass; public void setUsername(String username) {
this.username = username;
} public void setUserpass(String userpass) {
this.userpass = userpass;
} public EmailAuthenticator() {
} public EmailAuthenticator(String username, String userpass) {
this.username = username;
this.userpass = userpass;
}
public PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(username,userpass);
} }
创建Mail类设置邮件信息:
package cn.mail; import java.util.Date;
import java.util.Properties; import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage; public class Mail {
private String mailServer,from,to,mailSubject,mailContent;
private String username,password;
public Mail(){
//设置邮件信息
//进行认证登录的用户名
username="zt@mail.com";
//认证密码
password="zt";
//认证的邮箱对应的邮件服务器
mailServer="192.168.17.173";
//发件人信息
from="zt";
//收件人信息
to="jpp@mail.com";
//邮件标题
mailSubject="呵呵";
//邮件内容
mailContent="呵呵火狐";
}
//设置邮件服务器
@SuppressWarnings("static-access")
public void send(){
Properties prop=System.getProperties();
//指定邮件server
prop.put("mail.smtp.host", mailServer); //是否开启认证
prop.put("mail.smtp.auth", "true"); //smtp协议的
prop.put("mail.smtp.port", "25");
//产生Session服务
EmailAuthenticator mailauth=new EmailAuthenticator(username, password);
Session mailSession=Session.getInstance(prop,(Authenticator)mailauth);
try {
//封装Message对象
Message message=new MimeMessage(mailSession); message.setFrom(new InternetAddress(from)); //发件人
message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));//收件人
message.setSubject(mailSubject);
//设置内容(设置字符集处理乱码问题)
message.setContent(mailContent,"text/html;charset=gbk");
message.setSentDate(new Date());
//创建Transport实例,发送邮件
Transport tran=mailSession.getTransport("smtp");
tran.send(message,message.getAllRecipients());
tran.close(); } catch (Exception e) {
e.printStackTrace();
}
}
}
测试类:
package cn.mail; public class Test {
public static void main(String[] args) {
Mail mail=new Mail();
mail.send();
System.out.println("success!");
} }
发送带附件的Mail
MailWithAttachment:
package cn.bdqn; import java.io.IOException; import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility; import org.springframework.core.io.ClassPathResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper; public class MailWithAttachment {
private JavaMailSender mailSender; //必须使用 JavaMailSender
public void setMailSender(JavaMailSender mailSender) {
this.mailSender = mailSender;
} public void send() throws MessagingException,IOException{
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
helper.setFrom("zt@mail.com");
helper.setTo("jpp@mail.com"); helper.setSubject("问好");
helper.setText("好久不见,最近好吗?");
//添加附件1
ClassPathResource file1 = new ClassPathResource(
"/cn/bdqn/attachfiles/test.doc");
helper.addAttachment(file1.getFilename(), file1.getFile());
//添加附件2:附件的文件名为中文时,需要对文件名进行编码转换,解决乱码问题
ClassPathResource file2 = new ClassPathResource(
"/cn/bdqn/attachfiles/附件测试文件.doc");
helper.addAttachment(MimeUtility.encodeWord(file2.getFilename()),file2.getFile());
mailSender.send(mimeMessage);
}
}
测试类:
package cn.bdqn; import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class MailTest {
public static void main(String[] args){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); /*测试带附件的邮件*/
try{
MailWithAttachment mailWithAttach = (MailWithAttachment)context.getBean("mailWithAttachment");
mailWithAttach.send();
}catch(Exception e){
System.out.print(e.toString());
}
}
}
applicationContext.xml:大配置
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
<bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="192.168.17.173"></property><!-- 服务器 -->
<property name="port" value="25"></property><!-- 端口 -->
<property name="username" value="jpp"></property><!-- 用户名 -->
<property name="password" value="jpp"></property><!-- 密码 -->
<property name="protocol" value="smtp" ></property><!-- 协议 -->
<property name="defaultEncoding" value="utf-8"></property><!-- 默认编码 -->
<property name="javaMailProperties">
<props>
<!-- 设置SMTP服务器需要用户验证 -->
<prop key="mail.smtp.auth">true</prop>
</props>
</property>
</bean> <bean id="mailWithAttachment" class="cn.bdqn.MailWithAttachment">
<property name="mailSender" ref="mailSender"></property>
</bean> </beans>
发送带图片的mail
Mail.com
package cn.bdqn.pojo; import java.io.File; public class Mail {
private String from;
private String to;
private String subject;
private String content;
private File file;
private String fileName; public Mail(){}
public Mail(String from, String to, String subject, String content, File file, String fileName){
this.from = from;
this.to = to;
this.subject = subject;
this.content = content;
this.file = file;
this.fileName = fileName;
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
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 File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
} }
MailService:
package cn.bdqn.service; import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility; import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper; import cn.bdqn.pojo.Mail; public class MailService {
private JavaMailSender mailSender; public void setMailSender(JavaMailSender mailSender) {
this.mailSender = mailSender;
}
public void sendMail(Mail mail){
try{
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
helper.setFrom("jpp@mail.com");
helper.setTo(mail.getTo()); helper.setSubject(mail.getSubject());
helper.setText(mail.getContent());
//(1)要直接使用带后缀的文件名全称, (2)需要处理中文乱码问题
helper.addAttachment(MimeUtility.encodeWord(mail.getFileName()),mail.getFile());
mailSender.send(mimeMessage);
}catch(Exception e){
e.printStackTrace();
}
}
}
SendMailAction:
package cn.bdqn.action; import java.io.File; import cn.bdqn.pojo.Mail;
import cn.bdqn.service.MailService; import com.opensymphony.xwork2.ActionSupport; public class SendMailAction extends ActionSupport{
private static final long serialVersionUID = 1L; private MailService mailService =null;
private String from;
private String to;
private String subject;
private String content;
private File upload;
private String uploadFileName; @Override
public String execute() throws Exception {
Mail mail = new Mail(getFrom(),getTo(),getSubject(),getContent(),getUpload(),getUploadFileName());
mailService.sendMail(mail); return "success";
} public void setMailService(MailService mailService) {
this.mailService = mailService;
} public File getUpload() {
return upload;
} public void setUpload(File upload) {
this.upload = upload;
}
public String getFrom() {
return from;
} public void setFrom(String from) {
this.from = from;
} public String getTo() {
return to;
} public void setTo(String to) {
this.to = to;
} 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 getUploadFileName() {
return uploadFileName;
} public void setUploadFileName(String uploadFileName) {
this.uploadFileName = uploadFileName;
}
}
applicationContext.xml:大配置
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd"> <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="192.168.8.71"></property><!-- 服务器 -->
<property name="port" value="25"></property><!-- 端口 -->
<property name="username" value="jpp"></property><!-- 用户名 -->
<property name="password" value="jpp"></property><!-- 密码 -->
<property name="protocol" value="smtp" ></property><!-- 协议 -->
<property name="defaultEncoding" value="utf-8"></property><!-- 默认编码 -->
<property name="javaMailProperties">
<props>
<!-- 设置SMTP服务器需要用户验证 -->
<prop key="mail.smtp.auth">true</prop>
</props>
</property>
</bean> <bean id="mailService" class="cn.bdqn.service.MailService">
<property name="mailSender" ref="mailSender"></property>
</bean> </beans>
struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<constant name="struts.i18n.encoding" value="UTF-8"/>
<package name="default" namespace="/" extends="struts-default">
<action name="sendmailAction" class="cn.bdqn.action.SendMailAction">
<result name="success">/sendmail_success.jsp</result>
</action>
</package> </struts>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<display-name></display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list> <!-- struts2的配置文件 -->
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<!-- <url-pattern>*.action</url-pattern> -->
<url-pattern>/*</url-pattern>
</filter-mapping> <!-- Spring的配置信息 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param> <listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- <filter>
<filter-name>OpenSessionInViewFilter</filter-name>
<filter-class>
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
</filter-class>
</filter> -->
<!-- <filter-mapping>
<filter-name>OpenSessionInViewFilter</filter-name>
<url-pattern>*.action</url-pattern>
</filter-mapping> -->
</web-app>
index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@taglib uri="/struts-tags" prefix="s"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>"> <title>邮件发送页</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head> <body>
<H2>邮件发送</H2><br>
<s:form action="sendmailAction" enctype="multipart/form-data" method="post">
<s:textfield name="from" label="发件人" value="tina@mail.com"/>
<s:textfield name="to" label="收件人"/>
<s:textfield name="subject" label="主题"/>
<s:textarea name="content" label="内容"/>
<s:file name="upload" lable="选择附件"/>
<s:submit name="submit" value="发送邮件"/>
</s:form> </body>
</html>
sendmail_success.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="/struts-tags" prefix="s"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>"> <title>成功页</title> <meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
--> </head> <body>
<H2>邮件发送成功!</H2>
</body>
</html>
Spring JavaMail发送邮件的更多相关文章
- 使用spring的JavaMail发送邮件
以前我们使用JavaMail发送邮件,步骤挺多的.现在的项目跟Spring整合的比较多.所以这里主要谈谈SpringMail发送. 导入jar包. 配置applicationContext-email ...
- JavaMail发送邮件第一版
首先,我们先来了解一个基本的知识点,用什么工具来发邮件? 简单的说一下,目前用的比较多的客户端:OutLook,Foxmail等 顺便了解一下POP3.SMTP协议的区别: POP3,全名为" ...
- java 利用spring JavaMailSenderImpl发送邮件,支持普通文本、附件、html、velocity模板
java 利用spring JavaMailSenderImpl发送邮件,支持普通文本.附件.html.velocity模板 博客分类: Java Spring 本文主要介绍利用JavaMailS ...
- JAVAEE——BOS物流项目13:Quartz概述、创建定时任务、使用JavaMail发送邮件、HighCharts概述、实现区域分区分布图
1 学习计划 1.Quartz概述 n Quartz介绍和下载 n 入门案例 n Quartz执行流程 n cron表达式 2.在BOS项目中使用Quartz创建定时任务 3.在BOS项目中使用Jav ...
- 使用JavaMail发送邮件-从FTP读取图片并添加到邮件正文发送
业务分析: 最近工作需要,需要从FTP读取图片内容,添加到邮件正文发送.发送邮件正文,添加附件采用Spring的MimeMessageHelper对象来完成,添加图片也将采用MimeMessageHe ...
- 使用JavaMail发送邮件-no object DCH for MIME type multipart/mixed报错解决
最近需要实现一个使用Spring schedule按一定时间间隔自动触发条件发送邮件的功能,在开发的过程中,是按照先测试能发出text/html文本邮件,然后测试添加附件发送邮件,我碰到的问题是,文本 ...
- 47. Spring Boot发送邮件【从零开始学Spring Boot】
(提供源代码) Spring提供了非常好用的JavaMailSender接口实现邮件发送.在Spring Boot的Starter模块中也为此提供了自动化配置.下面通过实例看看如何在Spring Bo ...
- JavaMail发送邮件
发送邮件包含的内容有: from字段 --用于指明发件人 to字段 --用于指明收件人 subject字段 --用于说明邮件主题 cc字段 -- 抄送,将邮件发送给收件人的同时抄 ...
- web应用中使用JavaMail发送邮件
现在很多的网站都提供有用户注册功能, 通常我们注册成功之后就会收到一封来自注册网站的邮件.邮件里面的内容可能包含了我们的注册的用户名和密码以及一个激活账户的超链接等信息.今天我们也来实现一个这样的功能 ...
随机推荐
- ASP.NET Core的配置(5):配置的同步[ 实例篇]
ConfigurationBuilder在生成以Configuration对象的时候会利用注册其中的ConfigurationProvider加载原始的配置数据,那么一旦配置源中的数据发生变化,应用程 ...
- YYModel 源码解读(二)之YYClassInfo.h (2)
/** Instance variable information. */ @interface YYClassIvarInfo : NSObject @property (nonatomic, as ...
- 现代3D图形编程学习-环境设置
本书系列 现代3D图形编程学习 环境设置 由于本书中的例子,均是基于OpenGL实现的,因此你的工作环境需要能够运行OpenGL,为了读者能够更好的运行原文中的示例,此处简单地介绍了linux和win ...
- FFmpeg学习1:视频解码
在视频解码前,先了解以下几个基本的概念: 编解码器(CODEC):能够进行视频和音频压缩(CO)与解压缩(DEC),是视频编解码的核心部分. 容器/多媒体文件(Container/File):没有了解 ...
- 细说Java主流日志工具库
概述 在项目开发中,为了跟踪代码的运行情况,常常要使用日志来记录信息. 在Java世界,有很多的日志工具库来实现日志功能,避免了我们重复造轮子. 我们先来逐一了解一下主流日志工具. java.util ...
- ES6笔记(5)-- Generator生成器函数
系列文章 -- ES6笔记系列 接触过Ajax请求的会遇到过异步调用的问题,为了保证调用顺序的正确性,一般我们会在回调函数中调用,也有用到一些新的解决方案如Promise相关的技术. 在异步编程中,还 ...
- Netty简介
Netty简介 Netty是由JBOSS提供的一个Java开源框架.Netty提供异步的.事件驱动的网络应用程序框架和工具,用以快速开发高性能.高可靠性的网络服务器和客户端程序.和传统BIO不同,NI ...
- Delphi_02_Delphi程序的结构
一.工程文件 program MultiUnit; {$APPTYPE CONSOLE} uses SysUtils, Unit1 in 'Unit1.pas'; begin //引用unit1中的变 ...
- javaweb
关于java,作为一个初学者,作为一个即将跨入其中的钻研者,我觉得我很必要好好地升入其中认真学习每一个环节
- MySQL数据库不能远程访问的解决办法
MySQL数据库不允许从远程访问怎么办? 下面提供两种方法: 1.改表法 MySQL的帐号不允许从远程登陆,只能在localhost.这个时候只要在localhost的那台电脑,登入mysql后,更改 ...