Spring 发送电子邮件

在学习spring之前先学习以下不用spring来实现javamail的邮件发送:

用到得jar包:

package com.css.service.email;

import java.security.Security;
import java.util.Date;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.URLName;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;


public class JavaMailSslSender {

 public static void main(String[] args) throws AddressException,
   MessagingException {
//  加密邮件有提供的类Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
  final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
  // Get a Properties object
  Properties props = System.getProperties();
  props.setProperty("mail.smtp.host", "smtp.gmail.com");服务主机地址
  props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
  props.setProperty("mail.smtp.socketFactory.fallback", "false");
  props.setProperty("mail.smtp.port", "465");端口
  props.setProperty("mail.smtp.socketFactory.port", "465");
  props.put("mail.smtp.auth", "true");是否要验证身份

//邮箱的用户名和密码
  final String username = "masterspring2";
  final String password = "spring";

验证用户名和密码
  Session session = Session.getDefaultInstance(props,
    new Authenticator() {
     protected PasswordAuthentication getPasswordAuthentication() {
      return new PasswordAuthentication(username, password);
     }
    });
  Message msg = new MimeMessage(session);

发送邮件地址

  msg.setFrom(new InternetAddress(username + "@gmail.com"));
  接受邮件地址
  msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(
    "dengjianli@126.com", false));
  msg.setSubject("Hello");
  msg.setText("How are you");
  msg.setSentDate(new Date());
  URLName urln = new URLName("smtps", "smtp.gmail.com", 465, null,"masterspring2", "spring");
        Transport t = session.getTransport(urln);
  t.send(msg);

  System.out.println("Message sent.");
 }
}

spring实现javamail:(用红色表注的请注意:需要改动的)

这里的发送邮件的服务器地址:masterspring2@gmail.com是可以接受服务的smtp协议。你也可以自己申请了一个邮箱地址。但是好像126、163邮箱的2007年11份之后申请的邮箱都不能用smtp服务。这里用的邮箱地址masterspring2@gmail.com是可以发送的。

用到jar包:

 

applicationContext.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

<beans>

 <bean id="propertyConfigurer"
  class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  <property name="locations">
   <list>
    <value>classpath:messages.properties</value>
   </list>
  </property>
 </bean>


 <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
  <property name="host">
   <value>${host}</value>
  </property>
  <property name="username">
   <value>${username}</value>
  </property>
  <property name="password">
   <value>${password}</value>
  </property>

  <property name="port">
   <value>${port}</value>
  </property>

  <property name="javaMailProperties">
   <props>
    <prop key="mail.smtp.auth">${mail.smtp.auth}</prop>
    <prop key="mail.smtp.timeout">${mail.smtp.timeout}</prop>
    <prop key="mail.debug">${mail.debug}</prop>
    <prop key="mail.smtp.starttls.enable">${mail.smtp.starttls.enable}</prop>
    <prop key="mail.smtp.socketFactory.class">${mail.smtp.socketFactory.class}</prop>
    <prop key="mail.smtp.socketFactory.fallback">${mail.smtp.socketFactory.fallback}</prop>

   </props>
  </property>

 </bean>


</beans>


messages.properties:

host=smtp.gmail.com
username=masterspring2
password=spring
port=465
mail.smtp.socketFactory.port=456
mail.debug=true
mail.smtp.auth=true
mail.smtp.timeout=25000
mail.smtp.starttls.enable=true
mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
mail.smtp.socketFactory.fallback=true
#from=masterspring2@gmail.com
#subject=\u6807\u9898
#text=\u5185\u5BB9\u554A

SpringMailImpl.java:

package com.css.springmail.test;


import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;

public class SpringMailImpl{

    
  
    /** *//**
     * 测试发送只有文本信息的简单测试
     * @param sender 邮件发送器
     * @throws Exception
     */
     public void sendTextMail(JavaMailSender sender) throws Exception {
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setTo("dengjianli@126.com");
        mailMessage.setFrom("masterspring2@gmail.com");
        mailMessage.setSubject("test by amigo");
        mailMessage.setText("spring Mail的简单测试123");
       mailMessage.setSentDate(new Date());
        sender.send(mailMessage);
        System.out.println("成功发送文本文件!");
    }
    
    /** *//**
     * 发送带附件的邮件
     * @param sender 邮件发送器 
     * @throws Exception
     */
    public void sendMimeMessage(final JavaMailSender sender) throws Exception {
        //附件文件集合
        final List files = new ArrayList();
        MimeMessagePreparator mimeMail = new MimeMessagePreparator() {
            public void prepare(MimeMessage mimeMessage) throws MessagingException {
                mimeMessage.setRecipient(Message.RecipientType.TO, 
                        new InternetAddress("dengjianli@126.com"));
                mimeMessage.setFrom(new InternetAddress("masterspring2@gmail.com"));
                mimeMessage.setSubject("Spring发送带附件的邮件", "gb2312"); 
                
                Multipart mp = new MimeMultipart();
                
                //向Multipart添加正文

                MimeBodyPart content = new MimeBodyPart();
                content.setText("内含spring邮件发送的例子,请查收!");
                
                //向MimeMessage添加(Multipart代表正文)
                mp.addBodyPart(content);
              //  files.add("com/css/springmail/test/SpringMail.java");
                files.add("e:/s.xml");
                
                //向Multipart添加附件
                Iterator it = files.iterator();
                sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
                while(it.hasNext()) {
                    MimeBodyPart attachFile = new MimeBodyPart();
                    String filename = it.next().toString();
                    FileDataSource fds = new FileDataSource(filename);
                    attachFile.setDataHandler(new DataHandler(fds));
                    attachFile.setFileName("=?GBK?B?"+enc.encode(fds.getName().getBytes())+"?=");
                    mp.addBodyPart(attachFile);
                }
                
                files.clear();
                
                //向Multipart添加MimeMessage
                mimeMessage.setContent(mp);
                mimeMessage.setSentDate(new Date());
            }
        };

        //发送带附件的邮件
        sender.send(mimeMail);
        
        System.out.println("成功发送带附件邮件!");
    }

    
    
    /** *//**
     * 发送带附件的html邮件
     * @param  邮件发送器 
     * @throws Exception
     */
    public void sendMimehtmlandmultiple() throws Exception {
     ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");   
        JavaMailSender mailSender= (JavaMailSender) context.getBean("mailSender");
     MimeMessage mime = mailSender.createMimeMessage();  
        MimeMessageHelper helper;   
        try {   
            helper = new MimeMessageHelper(mime,true,"utf-8");   
            helper.setFrom("masterspring2@gmail.com");   
            helper.setTo("dengjianli@126.com");   
            helper.setSubject(" 测试spring Mail的附件功能");   
            //需要将附件显示在html中   
            //在标签中用cid:xx 标记,使用helper.addInline()方法添加   
            helper.setText("<html><body>javaeye是个好网站:<br>"+   
                    "<a href='http://www.iteye.com'>" +   
                    "<img src='cid:logo'></a></body></html>",true);   
            helper.addInline("logo",new FileSystemResource("e:/s.xml"));   
            //helper.addAttachment("javaeye.gif", new ClassPathResource("javaeye.gif"));   
        } catch (MessagingException e) {   
            // TODO Auto-generated catch block   
            e.printStackTrace();   
        }   
       
        mailSender.send(mime);   
        System.out.println("成功发送带附件邮件!");
    } 
    
   
 

}

test.java:

package com.css.springmail.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.mail.javamail.JavaMailSender;

public class test {
  public static void main(String[] args) throws Exception {
         ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        JavaMailSender sender = (JavaMailSender) ctx.getBean("mailSender");
        SpringMailImpl springMail = new SpringMailImpl();
         //测试发送只有文本信息的简单测试
         springMail.sendTextMail(sender);

         //测试发送带附件的邮件
         //springMail.sendMimeMessage(sender);
         //发送html和附件
        // springMail.sendMimehtmlandmultiple();
     }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值