简单的发邮件功能实现

 

1.引入pom

<dependencies> 
     <dependency> 
           <groupId>org.springframework.boot</groupId> 
           <artifactId>spring-boot-starter-mail</artifactId> 
     </dependency>
 </dependencies>

2、在application.properties中添加邮箱配置

spring.mail.host=smtp.qiye.163.com //邮箱服务器地址
spring.mail.username=xxx@oo.com //用户名
spring.mail.password=xxyyooo    //密码
spring.mail.default-encoding=UTF-8

mail.fromMail.addr=xxx@oo.com  //以谁来发送邮件

实例: spring.mail.host=192.168.*.* spring.mail.username=wangwei3@inner.sss.com spring.mail.password=wangwei3 spring.mail.default-encoding=UTF-8 mail.fromMail.addr=wangwei3@inner.sss.com

3、编写mailService,这里只提供实现类。

@Component //或者@Service
public class MailServiceImpl implements MailService{
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private JavaMailSender mailSender;
@Value(
"${mail.fromMail.addr}")
private String from;
@Override
public void sendSimpleMail(String to, String subject, String content) { SimpleMailMessage message = new SimpleMailMessage(); message.setFrom(from); message.setTo(to); message.setSubject(subject); message.setText(content); try { mailSender.send(message); logger.info("简单邮件已经发送。"); } catch (Exception e) { logger.error("发送简单邮件时发生异常!", e); } } }

4、编写test类进行测试

@RunWith(SpringRunner.class)
@SpringBootTest
public class MailServiceTest {

    @Autowired
    private MailService MailService;

    @Test
    public void testSimpleMail() throws Exception {
        MailService.sendSimpleMail("ityouknow@126.com","test simple mail"," hello this is simple mail");
    }
}

到此一个简单的邮件发送就结束了,还可以发送内容丰富的其他邮件模板,请参考

https://www.cnblogs.com/ityouknow/p/6823356.html

但是有坑,常见错误

解决方案:

1.开启Telnet

 

2.添加:-Xms512m -Xmx800m -Djava.net.preferIPv4Stack=true

如果还不行,参考下面链接,一般要更改tomcat,https://my.oschina.net/itblog/blog/618842

 

posted @ 2019-01-08 13:59  隔壁w王叔叔  阅读(284)  评论(0编辑  收藏  举报