JavaMail 邮件发送

jar包部署

img

/**
 * 通过SMTP进行邮件集成
 */
public class CmpSendMail {
    // 邮件发送服务器主机
    private final static String HOST = "url";

    // 邮件发送协议
    private final static String PROTOCOL = "smtp";

    // 是否需要身份认证
    private final static String IS_AUTH = "true";

    // 发件人
    private static String from = "xx@qq.com";

    /**
     * 初始化连接右键服务器会话信息
     */
    private static Properties props = null;
    static {
        props = new Properties();
        props.setProperty("mail.transport.protocol", PROTOCOL);
        props.setProperty("mail.smtp.host", HOST);
        props.setProperty("mail.smtp.auth", IS_AUTH);
    }

    /**
     * 向服务器提交认证信息
     */
    static class MyAuthenticator extends Authenticator {
        private String username = "40545";

        private String password = "11111";

        public MyAuthenticator() {
            super();
        }

        public MyAuthenticator(String username, String password) {
            super();
            this.username = username;
            this.password = password;
        }

        public PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }
    }

    /**
     * cmp邮件集成
     * 
     * @param address
     */
    public static void sendCmpEmail(InternetAddress[] address, String theme,
            String content) throws Exception {

        // 获得邮件session实力对象
        Session session = Session.getInstance(props, new MyAuthenticator());

        // 创建MimeMessage实例对象
        MimeMessage msg = new MimeMessage(session);

        // 设置发件人
        msg.setFrom(new InternetAddress(from));

        // 设置收件人
        msg.setRecipients(RecipientType.TO, address);

        // 设置发送信息
        msg.setSentDate(new Date());

        // 设置邮件主题
        msg.setSubject(theme + "[系统提醒]");

        StringBuffer con = new StringBuffer();
        con.append("<a style='text-decoration: none;' href='"
                + content.toString() + "'>查看详情</a></p>");

        // 设置邮件文本内容
        msg.setContent(con, "text/html;charset=UTF-8");

        // 保存并生成最终的邮件内容
        msg.saveChanges();

        // 发送邮件
        Transport.send(msg);
    }

}

学习javaMail博客连接:

java发送邮件带url、html

JavaMail使用SMTP协议发送电子邮件(详解)

原文地址:https://www.cnblogs.com/yoci/p/10239608.html