发送邮件工具类

时间:2025-03-10 10:27:44
  • package ;
  • import .*;
  • import ;
  • import ;
  • import ;
  • public class MailUtil {
  • public static void sendTextMail(final String to, final String subject,final String content){
  • String host = "smtp.";
  • String user = ""; //你的邮箱账号
  • String password= ""; //你的邮箱授权码
  • try {
  • sendTextMail(host, user, password, to, subject, content);
  • } catch (Exception e) {
  • ();
  • }
  • }
  • public static void sendTextMail(final String host, final String user, final String password,
  • final String to, final String subject, final String content) throws Exception {
  • // 相关的属性
  • Properties props = new Properties();
  • ("", host);
  • ("", "true");
  • ("", "20000");
  • // 设置 电子邮箱和密码,做发送邮件的授权
  • Authenticator auth = new Authenticator() {
  • @Override
  • protected getPasswordAuthentication() {
  • return new PasswordAuthentication(user, password);
  • }
  • };
  • Session session = (props, auth);
  • // 定义要发送邮件的内容
  • MimeMessage msg = new MimeMessage(session);
  • // 设置发送放的电子邮箱
  • (new InternetAddress(user));
  • // 接收方的电子邮箱
  • (.TO, new InternetAddress(to));
  • // 标题,主题
  • (subject);
  • // 发送的文本内容
  • (content);
  • // 保存邮件
  • ();
  • Transport.send(msg, ());
  • }
  • }