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,并植入用户名和密码
packagecn.mail;importjavax.mail.Authenticator;importjavax.mail.PasswordAuthentication;public class EmailAuthenticator extendsAuthenticator {privateString username;privateString userpass;public voidsetUsername(String username) {this.username =username;
}public voidsetUserpass(String userpass) {this.userpass =userpass;
}publicEmailAuthenticator() {
}publicEmailAuthenticator(String username, String userpass) {this.username =username;this.userpass =userpass;
}publicPasswordAuthentication getPasswordAuthentication(){return newPasswordAuthentication(username,userpass);
}
}
View Code
创建Mail类设置邮件信息:
packagecn.mail;importjava.util.Date;importjava.util.Properties;importjavax.mail.Authenticator;importjavax.mail.Message;importjavax.mail.Session;importjavax.mail.Transport;importjavax.mail.internet.InternetAddress;importjavax.mail.internet.MimeMessage;public classMail {privateString mailServer,from,to,mailSubject,mailContent;privateString username,password;publicMail(){//设置邮件信息//进行认证登录的用户名
username="zt@mail.com";//认证密码
password="zt";//认证的邮箱对应的邮件服务器
mailServer="192.168.17.173";//发件人信息
from="zt";//收件人信息
to="jpp@mail.com";//邮件标题
mailSubject="呵呵";//邮件内容
mailContent="呵呵火狐";
}//设置邮件服务器
@SuppressWarnings("static-access")public voidsend(){
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=newEmailAuthenticator(username, password);
Session mailSession=Session.getInstance(prop,(Authenticator)mailauth);try{//封装Message对象
Message message=newMimeMessage(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(newDate());//创建Transport实例,发送邮件
Transport tran=mailSession.getTransport("smtp");
tran.send(message,message.getAllRecipients());
tran.close();
}catch(Exception e) {
e.printStackTrace();
}
}
}
View Code
测试类:
packagecn.mail;public classTest {public static voidmain(String[] args) {
Mail mail=newMail();
mail.send();
System.out.println("success!");
}
}
View Code
发送带附件的Mail
MailWithAttachment:
packagecn.bdqn;importjava.io.IOException;importjavax.mail.MessagingException;importjavax.mail.internet.MimeMessage;importjavax.mail.internet.MimeUtility;importorg.springframework.core.io.ClassPathResource;importorg.springframework.mail.javamail.JavaMailSender;importorg.springframework.mail.javamail.MimeMessageHelper;public classMailWithAttachment {private JavaMailSender mailSender; //必须使用 JavaMailSender
public voidsetMailSender(JavaMailSender mailSender) {this.mailSender =mailSender;
}public void send() throwsMessagingException,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 = newClassPathResource("/cn/bdqn/attachfiles/test.doc");
helper.addAttachment(file1.getFilename(), file1.getFile());//添加附件2:附件的文件名为中文时,需要对文件名进行编码转换,解决乱码问题
ClassPathResource file2 = newClassPathResource("/cn/bdqn/attachfiles/附件测试文件.doc");
helper.addAttachment(MimeUtility.encodeWord(file2.getFilename()),file2.getFile());
mailSender.send(mimeMessage);
}
}
View Code
测试类:
packagecn.bdqn;importorg.springframework.context.ApplicationContext;importorg.springframework.context.support.ClassPathXmlApplicationContext;public classMailTest {public static voidmain(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());
}
}
}
View Code
applicationContext.xml:大配置
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">
true
View Code
发送带图片的mail
Mail.com
packagecn.bdqn.pojo;importjava.io.File;public classMail {privateString from;privateString to;privateString subject;privateString content;privateFile file;privateString fileName;publicMail(){}publicMail(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;
}publicString getFrom() {returnfrom;
}public voidsetFrom(String from) {this.from =from;
}publicString getTo() {returnto;
}public voidsetTo(String to) {this.to =to;
}publicString getSubject() {returnsubject;
}public voidsetSubject(String subject) {this.subject =subject;
}publicString getContent() {returncontent;
}public voidsetContent(String content) {this.content =content;
}publicFile getFile() {returnfile;
}public voidsetFile(File file) {this.file =file;
}publicString getFileName() {returnfileName;
}public voidsetFileName(String fileName) {this.fileName =fileName;
}
}
View Code
MailService:
packagecn.bdqn.service;importjavax.mail.internet.MimeMessage;importjavax.mail.internet.MimeUtility;importorg.springframework.mail.javamail.JavaMailSender;importorg.springframework.mail.javamail.MimeMessageHelper;importcn.bdqn.pojo.Mail;public classMailService {privateJavaMailSender mailSender;public voidsetMailSender(JavaMailSender mailSender) {this.mailSender =mailSender;
}public voidsendMail(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();
}
}
}
View Code
SendMailAction:
packagecn.bdqn.action;importjava.io.File;importcn.bdqn.pojo.Mail;importcn.bdqn.service.MailService;importcom.opensymphony.xwork2.ActionSupport;public class SendMailAction extendsActionSupport{private static final long serialVersionUID = 1L;private MailService mailService =null;privateString from;privateString to;privateString subject;privateString content;privateFile upload;privateString uploadFileName;
@Overridepublic String execute() throwsException {
Mail mail= newMail(getFrom(),getTo(),getSubject(),getContent(),getUpload(),getUploadFileName());
mailService.sendMail(mail);return "success";
}public voidsetMailService(MailService mailService) {this.mailService =mailService;
}publicFile getUpload() {returnupload;
}public voidsetUpload(File upload) {this.upload =upload;
}publicString getFrom() {returnfrom;
}public voidsetFrom(String from) {this.from =from;
}publicString getTo() {returnto;
}public voidsetTo(String to) {this.to =to;
}publicString getSubject() {returnsubject;
}public voidsetSubject(String subject) {this.subject =subject;
}publicString getContent() {returncontent;
}public voidsetContent(String content) {this.content =content;
}publicString getUploadFileName() {returnuploadFileName;
}public voidsetUploadFileName(String uploadFileName) {this.uploadFileName =uploadFileName;
}
}
View Code
applicationContext.xml:大配置
true
View Code
struts.xml
/sendmail_success.jsp
View Code
web.xml
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
index.jsp
struts2
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
struts2
/*
contextConfigLocation
classpath:applicationContext.xml
org.springframework.web.context.ContextLoaderListener
View Code
index.jsp
Stringpath=request.getContextPath();StringbasePath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%>
">
邮件发送页邮件发送
View Code
sendmail_success.jsp
Stringpath=request.getContextPath();StringbasePath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%>
">
成功页邮件发送成功!
View Code