Spring JavaMail发送邮件

Posted 나 는 당신

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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下使用需要指定这些文件的路径,在其它的操作系统上也类似。

   JavaMail是可选包,因此如果需要使用的话你需要首先从java.sun.com下载。目前最新版本是JavaMail1.4,使用JavaMail的时候需要Javabean Activation Framework的支持,因此你也需要下载JAF。安装JavaMail只是需要把他们加入到CLASSPATH中去,如果你不想修改CLASSPATH的话,可以直接把他们的jar包直接copy到JAVA_HOME/lib/ext下。这样JavaMail就安装好了。
 
  JavaMail包中用于处理电子邮件的核心类是:Session,Message,Address,Authenticator,Transport,Store,Folder等。Session定义了一个基本的邮件会话,它需要从Properties中读取类似于邮件服务器,用户名和密码等信息

 

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);
    }
    
}
View Code

创建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();
        }
  }
}
View Code

测试类:

package cn.mail;



public class Test {
    public static void main(String[] args) {
        Mail mail=new Mail();
        mail.send();
        System.out.println("success!");
    }

}
View Code

 

 

 发送带附件的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);
    }
}
View Code

测试类:

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());
        }
    }
}    
View Code

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>
View Code

发送带图片的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;
    }
    
    
}
View Code

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();
        }
    }
}
View Code

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;
    }
}
View Code

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>
View Code

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>    
View Code

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>
View Code

index.jsp