spring 邮件发送

xml配置:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:security="http://www.springframework.org/schema/security"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:flex="http://www.springframework.org/schema/flex"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd
       http://www.springframework.org/schema/flex
       http://www.springframework.org/schema/flex/spring-flex-1.0.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <context:property-placeholder location="classpath:/email.properties"/>

    <bean id="velocityEngine" class="org.springframework.ui.velocity.VelocityEngineFactoryBean">
      <property name="velocityProperties">
          <props>
          <prop key="resource.loader">class</prop>       
          <prop key="class.resource.loader.class">org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader</prop>       
          </props>
      </property>
   </bean>
    <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">  
        <property name="host" value="${email.host}" />  
        <property name="port" value="${email.port}" />  
        <property name="username" value="${email.username}" />  
        <property name="password" value="${email.password}" />  
        <property name="defaultEncoding" value="${email.encode}" />  
        <property name="javaMailProperties">  
            <props>  
                <prop key="mail.smtp.auth">${email.auth}</prop>  
            </props>  
        </property>  
    </bean>  
	<bean id="thirdVelocityEmailService" class="com.mongo.mail.ThirdVelocityEmailService">
		<property name="mailSender" ref="mailSender"></property> 
		<property name="velocityEngine" ref="velocityEngine"></property> 
	</bean>

</beans>

email.properties配置

email.host=smtp.163.com
email.port=25
email.username=test@163.com
email.password=1qaz!QAZ
email.auth=true
email.encode=utf-8
service实现:

package com.mongo.mail;
import java.io.File;
import java.util.Map;

import javax.mail.internet.MimeMessage;

import org.apache.velocity.app.VelocityEngine;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.ui.velocity.VelocityEngineUtils;

public class EmailService {

    private JavaMailSender  mailSender;
    private VelocityEngine velocityEngine;

    public void setMailSender(JavaMailSender  mailSender)
    {
       this.mailSender = mailSender;
    }

    public void setVelocityEngine(VelocityEngine velocityEngine)
    {
       this.velocityEngine = velocityEngine;
    }

    public void sendEmail(final Map<String,Object> model,
				    		final String subject,
				    		final String vmfile,
				    		final String[] mailTo,
				    		final String [] files){  
    	
    	 MimeMessagePreparator preparator = new MimeMessagePreparator() {
         //注意MimeMessagePreparator接口只有这一个回调函数
         public void prepare(MimeMessage mimeMessage) throws Exception{
            MimeMessageHelper message = new MimeMessageHelper(mimeMessage,true,"UTF-8");
            message.setTo(mailTo);//设置接收方的email地址
            message.setSubject(subject);//设置邮件主题
            message.setFrom("test@163.com");//设置发送方地址
            //从模板中加载要发送的内容,vmfile就是模板文件的名字
            //注意模板中有中文要加GBK,model中存放的是要替换模板中字段的值
            String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, vmfile,"UTF-8", model);
            //将发送的内容赋值给MimeMessageHelper,后面的true表示内容解析成html
            //如果您不想解析文本内容,可以使用false或者不添加这项
            message.setText(text, true);
            FileSystemResource file;
            for(String s:files)//添加附件
            {
               file = new FileSystemResource(new File(s));//读取附件
               message.addAttachment(s, file);//向email中添加附件
            }
          }
      };
       mailSender.send(preparator);//发送邮件
    }

}

test实现:

package com.mongo.mail;
import java.util.HashMap;
import java.util.Map;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class EmailTest {

    @Test
    public void sendEmail()
    {
       ApplicationContext context = new ClassPathXmlApplicationContext("applicationcontext-mail.xml");
       EmailService tves = (EmailService) context.getBean("emailService");
       Map<String,Object> model = new HashMap<String,Object>();
       model.put("userName","test");
       model.put("emailAddress", "123456@qq.com");
       //参数说明:替换velocity模板的变量和值对,邮件主题,velocity模板文件的路径,接收方email地址,附件
       //简单说明,如果您要群发,可以在接收方email地址中多传入几个email地址,附件可以一次发送多个
        tves.sendEmail(model,
		    		   "欢迎您的加入",
		    		   "com/mongo/mail/welcome.vm",
		    		   new String[]{"123456@qq.com"},
		    		   new String[]{"d:/Spring Security3.PDF"});
    }
}

vm:

<html>
<body>
<h3>您好 $!{userName}, 欢迎您加入!</h3>

<div>
    您的email地址是[$!{emailAddress}](mailto:${emailAddress}).
  本条信息是系统自动发送,请勿回复!
</div>
</body>

</html>



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用 Spring Boot 的邮件发送功能来发送电子邮件。首先,你需要在项目的依赖中添加 Spring Boot 的邮件依赖。在 `pom.xml` 文件中添加以下代码: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency> ``` 接下来,你需要在配置文件中配置邮件相关的属性。在 `application.properties`(或 `application.yml`)文件中添加以下属性: ```properties # 邮件服务器主机名 spring.mail.host=your-mail-host # 邮件服务器端口 spring.mail.port=your-mail-port # 邮件发送者用户名 spring.mail.username=your-username # 邮件发送者密码 spring.mail.password=your-password # 邮件发送者地址 spring.mail.from=your-email-address ``` 现在,你可以在你的代码中使用 `JavaMailSender` 接口来发送邮件。你可以注入 `JavaMailSender` 接口的实例,并使用 `send()` 方法发送邮件。以下是一个简单的示例: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.stereotype.Service; @Service public class EmailService { @Autowired private JavaMailSender javaMailSender; public void sendEmail(String to, String subject, String text) { SimpleMailMessage message = new SimpleMailMessage(); message.setTo(to); message.setSubject(subject); message.setText(text); javaMailSender.send(message); } } ``` 你可以在需要发送邮件的地方调用 `sendEmail()` 方法,并传入收件人地址、邮件主题和邮件内容。 这是使用 Spring Boot 发送邮件的基本步骤。你可以根据自己的需求进行进一步的定制和配置。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值