`
ssxxjjii
  • 浏览: 944850 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

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

分享到:
评论

相关推荐

    java发送邮件 spring发送邮件

    Spring框架以其模块化和灵活性而著名,它包含了一个名为`JavaMailSender`的接口,专门用于处理电子邮件的发送。在这个场景中,我们将深入探讨如何使用Spring框架发送邮件,以及涉及到的相关知识点。 首先,我们需要...

    spring发送邮件demo

    在Spring中,发送电子邮件的功能是通过Spring的Mail API实现的,这在系统监控、报警通知、用户验证等场景中非常常见。下面将详细介绍如何使用Spring发送邮件。 首先,我们需要在项目中引入Spring的邮件支持。这通常...

    java 发送邮件 spring发送邮件Mail

    Java发送邮件是软件开发中常见的需求,特别是在企业级应用中,用于发送通知、报表或验证用户的电子邮件地址。Spring框架提供了一种优雅的方式来处理这个任务,它整合了JavaMailSender接口和JavaMail API,使得在Java...

    spring各种邮件发送

    在"spring各种邮件发送"这个主题中,我们将探讨Spring框架如何帮助开发者实现电子邮件的发送。邮件服务在许多应用场景中都十分常见,例如用户注册确认、密码重置提醒等。 首先,Spring框架提供了`JavaMailSender`...

    spring JavaMailSenderImpl 发送邮件 java

    其中,Spring的JavaMailSenderImpl是用于发送电子邮件的一个重要工具,它使得开发者能够方便地集成邮件服务到他们的应用中。下面将详细介绍这个知识点。 **1. Spring的JavaMailSender接口与JavaMailSenderImpl实现*...

    Spring发送Email

    本文将深入探讨如何使用Spring发送电子邮件。 首先,我们需要了解Spring Mail的基本概念。Spring Mail是Spring框架的一个扩展,它基于JavaMail API,用于处理邮件发送任务。JavaMail API是Java中用于处理邮件的规范...

    Spring mvc 发送邮件功能

    在Spring MVC框架中,实现邮件发送功能通常涉及配置Spring的JavaMailSender接口和使用模板引擎如FreeMarker来创建动态邮件内容。以下是一个详细的步骤...这将使你的应用程序能够高效、灵活地发送各种类型的电子邮件。

    Spring发送邮件

    在Java编程领域,Spring框架是广泛应用的开源框架,它提供了许多功能,其中之一就是发送电子邮件。SpringMail是Spring框架的一个扩展,专门用于简化邮件发送过程。本文将深入探讨如何使用SpringMail来实现邮件发送...

    使用Spring Boot 开发支持多附件邮件发送微服务平台代码

    这个模块提供了发送电子邮件的能力,包括HTML内容、文本内容以及附件。在项目中,你需要在`pom.xml`或`build.gradle`文件中添加该依赖。 ```xml &lt;groupId&gt;org.springframework.boot &lt;artifactId&gt;spring-boot-...

    spring mail通过代理发送邮件

    标题中的“spring mail通过代理发送邮件”涉及到的是Spring框架中处理电子邮件发送的功能,尤其是在网络环境有限制或需要通过代理服务器的情况下。Spring Mail是Spring Framework的一个扩展模块,它提供了与JavaMail...

    Spring邮件发送

    在Java开发中,Spring框架提供了一种简单而强大的方式来发送电子邮件。Spring的`JavaMailSender`接口以及其实现类`SimpleMailMessage`和`MailMessage`,使得开发者能够轻松地集成邮件服务到应用程序中。这篇博客()...

    Spring mail发送邮件实例

    Spring Mail 是 Spring 框架中用于处理电子邮件发送的一个模块。它提供了一种简单的方式来进行邮件的发送,支持多种邮件发送协议,例如 SMTP 等,并且可以很好地与其他 Spring 组件集成。 #### 二、准备工作 在...

    Spring 使用163发邮件带附件

    标题 "Spring 使用163发邮件带附件" 涉及到的是在Java开发中,使用Spring框架发送电子邮件,特别是包含附件的邮件。这通常在系统需要自动化通知、报告发送或者用户验证过程中非常常见。Spring提供了JavaMailSender...

    Spring邮件发送服务(java邮件发送)

    在Java开发中,Spring框架提供了一种方便的方式来发送电子邮件,这就是SpringMail模块。SpringMail使得在应用程序中集成邮件服务变得更加简单,它支持多种功能,包括发送带有多个附件、多接收者(包括抄送和暗送)的...

    Spring Email 发送

    本示例将深入探讨如何使用Spring发送电子邮件,特别是针对中文乱码问题的解决方案。我们将涉及Spring的Java配置和Velocity模板引擎来创建动态邮件内容。 首先,我们需要引入必要的依赖。在Spring项目中,我们通常会...

    spring集成邮件服务

    JavaMail是一个开源库,它允许Java应用程序发送和接收电子邮件。它提供了一系列接口和类,用于操作邮件服务器,包括SMTP(简单邮件传输协议)、POP3(邮局协议)和IMAP(Internet消息访问协议)。 Spring框架通过`...

    使用springMail发送带附件的email

    SpringMail是一个在Java应用中发送电子邮件的库,它利用了JavaMail API的简便性和灵活性。在本项目中,我们将深入探讨如何使用SpringMail发送带有附件的电子邮件。首先,我们需要了解几个核心概念: 1. **JavaMail ...

    Spring Boot整合JavaMailSender发送电子邮件

    Spring提供了非常好用的JavaMailSender接口实现邮件发送。在Spring Boot的Starter模块中也为此提供了自动化配置。下面通过实例看看如何在Spring Boot中使用JavaMailSender发送邮件。

Global site tag (gtag.js) - Google Analytics