Java通过stmp协议发送邮件
本文实例为大家分享了Java通过stmp协议发送邮件的具体代码,供大家参考,具体内容如下
pom.xml 导入包
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> <version>2.1.7.RELEASE</version> </dependency>
application.properties 配置信息
## 邮箱配置 #spring.mail.host=smtp.163.com ## 你的163邮箱 #spring.mail.username=18603@163.com ## 注意这里不是邮箱密码,而是SMTP授权密码 #spring.mail.password=***** #spring.mail.port=25 #spring.mail.default-encoding=UTF-8 #spring.mail.from=18603@163.com
代码
package com.youjia.found.manager; import com.youjia.found.common.util.Check; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.FileSystemResource; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.stereotype.Component; import javax.annotation.Resource; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.io.File; /** * <P>邮件处理类</P> * * @author eric * @date 2020/2/6 11:08 AM * @since */ @Component public class MailManager { private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Value("${spring.mail.from}") private String from; @Autowired private JavaMailSender mailSender; /** * 带附件的邮件 * @param to 收件人 * @param subject 主题 * @param content 内容 * @param filePath 附件 */ public boolean sendMail(String to, String subject, String content, String filePath) { logger.info("stmp邮件发送 to:{}, subject:{}, content:{},filePath:{}", to, subject, content,filePath); boolean isOK=false; MimeMessage message = mailSender.createMimeMessage(); try { MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(from); //支持多个收件人 InternetAddress[] internetAddressTo = InternetAddress.parse(to); helper.setTo(internetAddressTo); helper.setSubject(subject); helper.setText(content, true); //附件 if(Check.notEmpty(filePath)){ FileSystemResource file = new FileSystemResource(new File(filePath)); String fileName = filePath.substring(filePath.lastIndexOf(File.separator)); helper.addAttachment(fileName, file); } mailSender.send(message); isOK= true; } catch (Exception e) { logger.error(e.getMessage(),e); isOK= false; } return isOK; } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。
赞 (0)