Jmail发送邮件工具类分享

时间:2022-10-02 18:29:32

 好久没更新博客了,实在是拖延症严重啊,好可怕,先更新个工具类吧,之前写的发送邮件的小工具,话不多说上代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import lombok.extern.slf4j.Slf4j;
 
import java.util.Properties;
 
import javax.mail.*;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
 
/**
 * <b>发送邮件工具类</b><br/>
 * <b>Create on:</b>2016/10/9 16:14<br/>
 *
 * @author : liud<br/>
 */
@Slf4j
public class SendMailUtil {
 
  /**
   * 发送邮件
   * @param smtpHost
   * @param fromUser
   * @param fromUserPassword
   * @param emailPort
   * @param toUser
   * @param subject
   * @param messageText
   */
  public static boolean doSendEmail(String smtpHost, final String fromUser,
                final String fromUserPassword, String userName, String emailPort, String toUser, String subject,
                String messageText) throws Exception {
    boolean flag = false;
    try {
      Properties props = new Properties();
      props.put("mail.smtp.host", smtpHost);
      props.put("mail.smtp.port", emailPort);
      props.put("mail.smtp.auth", "true");
      Session session = Session.getDefaultInstance(props, new Authenticator(){
        protected PasswordAuthentication getPasswordAuthentication() {
          return new PasswordAuthentication(fromUser, fromUserPassword);
        }});
      MimeMessage message = new MimeMessage(session);
      // 发件人
      InternetAddress from = new InternetAddress(fromUser);
      message.setFrom(from);
      // 收件人
      InternetAddress to = new InternetAddress(toUser);
      message.setRecipient(Message.RecipientType.TO, to);
      // 邮件标题
      message.setSubject(subject);
      // 邮件内容,也可以使纯文本"text/plain"
      message.setContent(messageText, "text/html;charset=GBK");
      message.saveChanges();
      Transport transport = session.getTransport("smtp");
      // smtp验证,就是你用来发邮件的邮箱用户名密码
      transport.connect(smtpHost, userName, fromUserPassword);
      // 发送
      transport.sendMessage(message, message.getAllRecipients());
      transport.close();
      flag = true;
    } catch (AddressException e) {
      log.error("地址异常:{}", e);
      throw e;
    } catch (MessagingException e) {
      log.error("消息异常:{}", e);
      throw e;
    } catch (Exception e) {
      log.error("系统异常:{}", e);
      throw e;
    }
 
    return flag;
  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。