标签:
在springMVC框架中使用邮件发送功能(非定时、只能发送指定的文本内容),具体的使用方法如下:
在pom文件中加入:
<dependency> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> <version>1.4.7</version> </dependency> <dependency> <groupId>org.apache.geronimo.specs</groupId> <artifactId>geronimo-activation_1.1_spec</artifactId> <version>1.1</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.9</version> </dependency>
在resources文件夹下,添加一个Email的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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd" default-lazy-init="true"> <description>Email配置</description> <bean id="smtpAuthenticator" class="com.ziqikeji.sdhdjk.utilities.email.SmtpAuthenticator"> <constructor-arg value="550380445@qq.com" ></constructor-arg> <constructor-arg value="6168697000" ></constructor-arg> </bean> <bean id="mailSession" class="javax.mail.Session" factory-method="getInstance"> <constructor-arg> <props> <prop key="mail.smtp.auth">true</prop> <prop key="mail.smtp.socketFactory.port">465</prop> <prop key="mail.smtp.socketFactory.class">javax.net.ssl.SSLSocketFactory</prop> <prop key="mail.smtp.socketFactory.fallback">false</prop> </props> </constructor-arg> <constructor-arg ref="smtpAuthenticator" /> </bean> <!-- 文本邮件服务类 --> <bean id="simpleMailService" class="com.ziqikeji.sdhdjk.utilities.email.SimpleMailService"> <property name="mailSender" ref="mailSender" /> <property name="freemarkerConfiguration" ref="freemarkerConfiguration" /> </bean> <!-- 邮件发送器 --> <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"> <property name="host" value="smtp.qq.com" /> <property name="port" value="25"/> <property name="session" ref="mailSession"/> <property name="defaultEncoding" value="UTF-8"/> </bean> </beans>
在web.xml中添加:
<context-param> <param-name>contextConfigLocation</param-name> <param-value> classpath*:/email/applicationContext-email.xml, ...... </param-value> </context-param>
至此,配置结束。
在src的项目文件夹中,添加一个纯文本邮件的服务类:
/** * 发送纯文本的用户修改通知邮件. */ public void sendMail() { try { MimeMessage msg = mailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(msg, true, DEFAULT_ENCODING); helper.setTo(“被发送者的邮箱”); helper.setFrom("发送者的邮箱"); helper.setSubject(“要发送的标题”); //要发送的内容,大家可以自己找方法,在这我就不具体说了 mailSender.send(msg); } catch (MessagingException e) { logger.error("构造邮件失败", e); } catch (Exception e) { logger.error("发送邮件失败", e); } }
在controller或service里边利用下面的代码调用:
邮件服务类名.sendMail();
标签:
原文地址:http://www.cnblogs.com/fxyh/p/4237242.html