spring JavaMailSenderImpl 发送邮件
spring JavaMailSenderImpl 发送邮件
wangmarke 发表于1年前
spring JavaMailSenderImpl 发送邮件
  • 发表于 1年前
  • 阅读 18
  • 收藏 0
  • 点赞 0
  • 评论 0

腾讯云 学生专属云服务套餐 10元起购>>>   

摘要: spring JavaMailSenderImpl 发送邮件

邮箱先开通这些服务

 

代码

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.Properties;

import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

/** * @author markee * */
public class EmailSender {
	private JavaMailSenderImpl javaMailSenderImpl;

	public EmailSender() {
		javaMailSenderImpl = new JavaMailSenderImpl();
		javaMailSenderImpl.setHost("smtp.发件服务器域名");
		javaMailSenderImpl.setUsername("用户名");
		// 这里有坑 有授权码用授权码,去邮箱里设置,开通权限 POP3/IMAP/SMTP服务
		javaMailSenderImpl.setPassword("授权码or密码");
		Properties properties = new Properties();
		// 设置为true,否则可能报553
		properties.setProperty("mail.smtp.auth", "true");
		properties.setProperty("mail.smtp.from", "用户名");
		properties.setProperty("mail.debug", "true");
		javaMailSenderImpl.setJavaMailProperties(properties);
	}

	public void sendEmail(String email, String fileName, String filePath) {
		MimeMessage mimeMessage = javaMailSenderImpl.createMimeMessage();
		try {
			MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(
					mimeMessage, true, "UTF-8");
			mimeMessageHelper.setFrom(new InternetAddress(
					javax.mail.internet.MimeUtility.encodeText("邮箱昵称") + "<"
							+ "用户名" + ">"));
			mimeMessageHelper.setTo(email);
			mimeMessageHelper.setSubject("主题");
			mimeMessageHelper.setText("内容", true);
			mimeMessageHelper.addAttachment(fileName, new File(filePath));
			javaMailSenderImpl.send(mimeMessage);
		} catch (MessagingException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		new EmailSender().sendEmail("xxxxxxx@qq.com", "", "");
	}
}

 

共有 人打赏支持
粉丝 5
博文 20
码字总数 7505
×
wangmarke
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: