1、引入相关jar包
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
<version>1.7</version>
</dependency>
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-tools</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.3.9.RELEASE</version>
</dependency>
Spring的基本核心jar包没有在上面写出来
2、编辑spring配置文件
<bean id="webEmailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
<property name="host" value="smtp.126.com" />
<property name="port" value="25" />
<property name="username" value="XXXXX@126.com" />
<property name="password" value="**********" />
<property name="javaMailProperties">
<props>
<!--设置是否需要身份验证 -->
<prop key="mail.smtp.auth">true</prop>
</props>
</property>
</bean>
<bean id="smg" class="org.springframework.mail.SimpleMailMessage">
<property name="from" value="你的发送邮箱" />
<property name="to" value="你的接受邮箱" />
</bean>
<bean id="velocityEngine"
class="org.springframework.ui.velocity.VelocityEngineFactoryBean">
<property name="velocityProperties">
<props>
<prop key="file.resource.loader.cache">false</prop>
<prop key="file.resource.loader.modificationCheckInterval">3</prop>
<prop key="resource.loader">file</prop>
<prop key="file.resource.loader.path">.</prop>
<prop key="file.resource.loader.class">
org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
</prop>
<prop key="velocimacro.library"></prop>
<prop key="input.encoding">UTF-8</prop>
<prop key="output.encoding">UTF-8</prop>
<prop key="default.contentType">application/x-www-form-urlencoded; charset=UTF-8</prop>
</props>
</property>
</bean>
@Controller
@RequestMapping("/mail")
public class WebEmail {
@Resource(name = "webEmailSender")
private JavaMailSenderImpl mailSender;
@Resource(name = "smg")
private SimpleMailMessage MailMessage;
@Resource
private VelocityEngine velocityEngine;
@RequestMapping(value="test1", method=RequestMethod.GET)
@ResponseBody
public void send(@RequestParam("s") String s) {
System.out.println(s);
try {
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
messageHelper.setFrom(MailMessage.getFrom());
messageHelper.setSubject(s); //主题
Map<String, Object> map = new HashMap<String, Object>();
map.put("username", "xxxx");
map.put("url", "http://www.baidu.com");
map.put("email", "gjni@worthtech.net");
String result = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "config/welcome.vm", "UTF-8",map);
messageHelper.setText(result, true); //内容
messageHelper.setTo(MailMessage.getTo()); //发送给
mailSender.send(mimeMessage); //发送邮件
} catch (Exception e) {
e.printStackTrace();
}
}
}
MimeMessageHelper(mimeMessage, true, "UTF-8") 要设置成UTF-8 ,如果不这样会发现,发送的邮件内容中文为乱码