今天给你们带来的是用java发送邮件,若有不足之处,敬请指教。html
本次咱们利用QQ来发送邮件。java
图示 |
---|
![]() |
图示 |
---|
![]() |
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd"> <context:component-scan base-package="com.xkt"></context:component-scan> <!-- 配置邮件发送类 --> <bean name="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"> <!-- 指定邮件的编码 --> <property name="defaultEncoding" value="UTF-8"></property> <!-- 指定邮件的服务器 --> <property name="host" value="smtp.qq.com"></property> <!-- 指定发送人的邮箱 --> <property name="username" value="这里填入邮箱帐号"></property> <!-- 指定发送人的密码 --> <property name="password" value="这里填入邮箱受权的密码"></property> <!-- 指定发送的邮箱服务器是需求认证的 --> <property name="javaMailProperties"> <value> mail.smtp.auth=true </value> </property> </bean> </beans>
package com.xkt.service; import java.util.Date; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mail.MailSender; import org.springframework.mail.SimpleMailMessage; import org.springframework.stereotype.Service; /** * @author lzx * */ @Service public class MailService { @Autowired private MailSender mailSender; /** * 发送邮件 */ public void send() { SimpleMailMessage message = new SimpleMailMessage(); message.setTo("这里填入要发送到的邮箱"); message.setText("Hello"); message.setSubject("title"); message.setFrom("******"); message.setSentDate(new Date()); mailSender.send(message); } }
package com.xkt.test; import org.junit.Test; import org.springframework.beans.BeansException; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.xkt.service.MailService; /** * @author lzx * */ public class MailServiceTest { @Test public void send() { try { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext( "classpath:applicationContext.xml"); MailService mailService = context.getBean(MailService.class); // 发送邮件 mailService.send(); context.close(); } catch (BeansException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
版权说明:欢迎以任何方式进行转载,但请在转载后注明出处!spring