zoukankan      html  css  js  c++  java
  • java mail 封装工具类使用

    直接上代码

    配置QQ邮箱的IMAP

    进入qq电子邮件点击 设置->账户里开启 SMTP 服务(开启IMAP/SMTP服务) 注意:在启用QQ邮箱的14天之后才能开启此服务

    创建Sendmail 类 

    导入这两个jar :

    public class Sendmail {
    private static final Log logger = LogFactory.getLog(Sendmail.class);


    public static Map<String,Object> sendTextMail(String strMail, String strTitle, String strText){
    Map<String,Object> map = new HashMap<String, Object>();
    String sends=null;
    Properties prop = new Properties();
    // 开启debug调试,以便在控制台查看
    prop.setProperty("mail.debug", "true"); 
    // 设置邮件服务器主机名
    prop.setProperty("mail.host", "smtp.qq.com");
    // 发送服务器需要身份验证
    prop.setProperty("mail.smtp.auth", "true");
    // 发送邮件协议名称
    prop.setProperty("mail.transport.protocol", "smtp");

    // 开启SSL加密,否则会失败
    try {
    MailSSLSocketFactory sf = new MailSSLSocketFactory();
    sf.setTrustAllHosts(true);
    prop.put("mail.smtp.ssl.enable", "true");
    prop.put("mail.smtp.ssl.socketFactory", sf);

    // 创建session
    Session session = Session.getInstance(prop);
    // 通过session得到transport对象
    Transport ts = session.getTransport();
    // 连接邮件服务器:邮箱类型,帐号,授权码代替密码(更安全)
    ts.connect("smtp.qq.com","****", "mddbpoilzjhidcjh");//后面的字符是授权码
    // 创建邮件
    MimeMessage message = new MimeMessage(session);
    // 指明邮件的发件人
    message.setFrom(new InternetAddress("*****@qq.com"));
    // 指明邮件的收件人,现在发件人和收件人是一样的,那就是自己给自己发
    message.setRecipient(Message.RecipientType.TO, new InternetAddress(strMail));
    // 邮件的标题
    message.setSubject(strTitle);
    // 邮件的文本内容
    message.setContent("<font style='color:red'>"+strText+"</font>", "text/html;charset=UTF-8");
    // 发送邮件
    ts.sendMessage(message, message.getAllRecipients());
    ts.close();
    } catch (Exception e) {
    logger.error("发送邮件异常");
    return (Map<String, Object>) map.put(sends, "发送邮件异常");
    }

    return (Map<String, Object>) map.put(sends, "发送邮件成功");
    }

    /* public static void main(String[] args) {
    try {
    Sendmail.sendTextMail("****@163.com","日志容量告警","测试邮件发送");
    } catch (Exception e) {
    // TODO: handle exception
    }

    }*/
    }

    代码调用工具类的方法为:

    try {

            //发送人的邮箱,   邮件标题,邮件内容
    Sendmail.sendTextMail("***@163.com","日志容量告警","终于解决了");
    } catch (Exception e) {
    e.printStackTrace();
    }

  • 相关阅读:
    GitLab用户权限管理
    类似vant中的tab实现
    Gitgitee/github/gitlab账号分离
    Vim操作
    partition by 用法
    crontab执行feat_gen.sh时,报错找不到pyspark
    SQL同一个字段出现null和0值,有何区别,原因是什么?left join导致null值出现,case when导致0值出现
    linux 定时任务crontab的用法
    卡方检验
    ROC与AUC
  • 原文地址:https://www.cnblogs.com/zxy-come-on/p/10881403.html
Copyright © 2011-2022 走看看