java 发送html 格式的邮件,QQ服务器或其他服务器(简单-复杂)

1.简单方式

-填好参数后,可直接执行main() 方法可以直接发送邮件

-可以发送不同smtp服务器

public class SendMail {
    public static void main(String[] args) {
        // 收件人电子邮箱
        String to = "***@qq.com";

        // 发件人电子邮箱
        String from = "***@qq.com";

        // 发件人电子邮箱密码
        String password = "***";

        // 指定发送邮件的主机
        String host = "smtp.qq.com";

        // 获取系统属性
        Properties properties = System.getProperties();

        // 设置邮件服务器
        properties.setProperty("mail.smtp.host", host);
        properties.setProperty("mail.smtp.auth", "true");
        properties.setProperty("mail.smtp.port", "587");//465 可能会失败,尝试用587
        properties.setProperty("mail.smtp.socketFactory.class",                 "javax.net.ssl.SSLSocketFactory");

        // 获取默认的 Session 对象
        Session session = Session.getDefaultInstance(properties, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(from, password);
            }
        });

        try {
            // 创建一个默认的 MimeMessage 对象MimeMessagemessage=newMimeMessage(session);
            MimeMessage message = new MimeMessage(session);
            // 设置 From: 头部头字段
            message.setFrom(new InternetAddress(from));

            // 设置 To: 头部头字段
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

            // 设置 Subject: 头部头字段
            message.setSubject("HTML邮件");

            // 设置消息体
            String htmlContent = "<p>测试--:</p>\n" +
                    "<p>&nbsp; &nbsp; &nbsp; &nbsp;{warnInfo}</p>\n" +
                    "<p>&nbsp; &nbsp; &nbsp; &nbsp;如有问题请联系***</p>\n" +
                    "<p>大数据中心</p>";//内容
            message.setContent(htmlContent, "text/html;charset=utf-8");

            // 发送消息
            Transport.send(message);
            System.out.println("邮件发送成功。");
        } catch (
                MessagingException mex) {
            mex.printStackTrace();
        }
    }
}

2.复杂方式

不依赖port

public class MailUtil {

    private MimeMessage mimeMsg; //MIME邮件对象
    private Session session; //邮件会话对象
    private Properties props; //系统属性
    private boolean needAuth = false; //smtp是否需要认证
    //smtp认证用户名和密码
    private String username;
    private String password;
    private Multipart mp; //Multipart对象,邮件内容,标题,附件等内容均添加到其中后再生成MimeMessage对象

    /**
     * Constructor
     * @param smtp 邮件发送服务器
     */
    public MailUtil(String smtp){
        setSmtpHost(smtp);
        createMimeMessage();
    }

    /**
     * 设置邮件发送服务器
     * @param hostName String
     */
    public void setSmtpHost(String hostName) {
        System.out.println("设置系统属性:mail.smtp.host = "+hostName);
        if(props == null)
            props = System.getProperties(); //获得系统属性对象
        props.put("mail.smtp.host",hostName); //设置SMTP主机
    }


    /**
     * 创建MIME邮件对象
     * @return
     */
    public boolean createMimeMessage()
    {
        try {
            System.out.println("准备获取邮件会话对象!");
            session = Session.getDefaultInstance(props,null); //获得邮件会话对象
        }
        catch(Exception e){
            System.err.println("获取邮件会话对象时发生错误!"+e);
            return false;
        }

        System.out.println("准备创建MIME邮件对象!");
        try {
            mimeMsg = new MimeMessage(session); //创建MIME邮件对象
            mp = new MimeMultipart();

            return true;
        } catch(Exception e){
            System.err.println("创建MIME邮件对象失败!"+e);
            return false;
        }
    }

    /**
     * 设置SMTP是否需要验证
     * @param need
     */
    public void setNeedAuth(boolean need) {
        System.out.println("设置smtp身份认证:mail.smtp.auth = "+need);
        if(props == null) props = System.getProperties();
        if(need){
            props.put("mail.smtp.auth","true");
        }else{
            props.put("mail.smtp.auth","false");
        }
    }

    /**
     * 设置用户名和密码
     * @param name
     * @param pass
     */
    public void setNamePass(String name,String pass) {
        username = name;
        password = pass;
    }

    /**
     * 设置邮件主题
     * @param mailSubject
     * @return
     */
    public boolean setSubject(String mailSubject) {
        System.out.println("设置邮件主题!");
        try{
            mimeMsg.setSubject(mailSubject);
            return true;
        }
        catch(Exception e) {
            System.err.println("设置邮件主题发生错误!");
            return false;
        }
    }

    /**
     * 设置邮件正文
     * @param mailBody String
     */
    public boolean setBody(String mailBody) {
        try{
            BodyPart bp = new MimeBodyPart();
            bp.setContent(""+mailBody,"text/html;charset=GBK");
            mp.addBodyPart(bp);

            return true;
        } catch(Exception e){
            System.err.println("设置邮件正文时发生错误!"+e);
            return false;
        }
    }
    /**
     * 添加附件
     * @param filename String
     */
    public boolean addFileAffix(String filename) {
        System.out.println("增加邮件附件:"+filename);
        try{
            BodyPart bp = new MimeBodyPart();
            FileDataSource fileds = new FileDataSource(filename);
            bp.setDataHandler(new DataHandler(fileds));
            bp.setFileName(MimeUtility.encodeText(fileds.getName()));
            mp.addBodyPart(bp);
            return true;
        } catch(Exception e){
            System.err.println("增加邮件附件:"+filename+"发生错误!"+e);
            return false;
        }
    }

    /**
     * 设置发信人
     * @param from String
     */
    public boolean setFrom(String from) {
        System.out.println("设置发信人!");
        try{
            mimeMsg.setFrom(new InternetAddress(from)); //设置发信人
            return true;
        } catch(Exception e) {
            return false;
        }
    }
    /**
     * 设置收信人
     * @param to String
     */
    public boolean setTo(String to){
        if(to == null)return false;
        try{
            mimeMsg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
            return true;
        } catch(Exception e) {
            return false;
        }
    }

    /**
     * 设置抄送人
     * @param copyto String
     */
    public boolean setCopyTo(String copyto)
    {
        if(copyto == null)return false;
        try{
            mimeMsg.setRecipients(Message.RecipientType.CC,(Address[]) InternetAddress.parse(copyto));
            return true;
        }
        catch(Exception e)
        { return false; }
    }

    /**
     * 发送邮件
     */
    public boolean sendOut()
    {
        try{
            mimeMsg.setContent(mp);
            mimeMsg.saveChanges();
            System.out.println("正在发送邮件....");

            Session mailSession = Session.getInstance(props,null);
            Transport transport = mailSession.getTransport("smtp");
            transport.connect((String)props.get("mail.smtp.host"),username,password);
            transport.sendMessage(mimeMsg,mimeMsg.getRecipients(Message.RecipientType.TO));
            //transport.sendMessage(mimeMsg,mimeMsg.getRecipients(Message.RecipientType.CC));
            //transport.send(mimeMsg);

            System.out.println("发送邮件成功!");
            transport.close();

            return true;
        } catch(Exception e) {
            e.printStackTrace();
            System.err.println("邮件发送失败!"+e);
            return false;
        }
    }

    /**
     * 调用sendOut方法完成邮件发送
     * @param smtp
     * @param from
     * @param to
     * @param subject
     * @param content
     * @param username
     * @param password
     * @return boolean
     */
    public static boolean send(String smtp,String from,String to,String subject,String content,String username,String password) {
        MailUtil theMailUtil = new MailUtil(smtp);
        theMailUtil.setNeedAuth(true); //需要验证

        if(!theMailUtil.setSubject(subject)) return false;
        if(!theMailUtil.setBody(content)) return false;
        if(!theMailUtil.setTo(to)) return false;
        if(!theMailUtil.setFrom(from)) return false;
        theMailUtil.setNamePass(username,password);

        if(!theMailUtil.sendOut()) return false;
        return true;
    }

    /**
     * 调用sendOut方法完成邮件发送,带抄送
     * @param smtp
     * @param from
     * @param to
     * @param copyto
     * @param subject
     * @param content
     * @param username
     * @param password
     * @return boolean
     */
    public static boolean sendAndCc(String smtp,String from,String to,String copyto,String subject,String content,String username,String password) {
        MailUtil theMailUtil = new MailUtil(smtp);
        theMailUtil.setNeedAuth(true); //需要验证

        if(!theMailUtil.setSubject(subject)) return false;
        if(!theMailUtil.setBody(content)) return false;
        if(!theMailUtil.setTo(to)) return false;
        if(!theMailUtil.setCopyTo(copyto)) return false;
        if(!theMailUtil.setFrom(from)) return false;
        theMailUtil.setNamePass(username,password);

        if(!theMailUtil.sendOut()) return false;
        return true;
    }

    /**
     * 调用sendOut方法完成邮件发送,带附件
     * @param smtp
     * @param from
     * @param to
     * @param subject
     * @param content
     * @param username
     * @param password
     * @param filename 附件路径
     * @return
     */
    public static boolean send(String smtp,String from,String to,String subject,String content,String username,String password,String filename) {
        MailUtil theMailUtil = new MailUtil(smtp);
        theMailUtil.setNeedAuth(true); //需要验证

        if(!theMailUtil.setSubject(subject)) return false;
        if(!theMailUtil.setBody(content)) return false;
        if(!theMailUtil.addFileAffix(filename)) return false;
        if(!theMailUtil.setTo(to)) return false;
        if(!theMailUtil.setFrom(from)) return false;
        theMailUtil.setNamePass(username,password);

        if(!theMailUtil.sendOut()) return false;
        return true;
    }

    /**
     * 调用sendOut方法完成邮件发送,带附件和抄送
     * @param smtp
     * @param from
     * @param to
     * @param copyto
     * @param subject
     * @param content
     * @param username
     * @param password
     * @param filename
     * @return
     */
    public static boolean sendAndCc(String smtp,String from,String to,String copyto,String subject,String content,String username,String password,String filename) {
        MailUtil theMailUtil = new MailUtil(smtp);
        theMailUtil.setNeedAuth(true); //需要验证

        if(!theMailUtil.setSubject(subject)) return false;
        if(!theMailUtil.setBody(content)) return false;
        if(!theMailUtil.addFileAffix(filename)) return false;
        if(!theMailUtil.setTo(to)) return false;
        if(!theMailUtil.setCopyTo(copyto)) return false;
        if(!theMailUtil.setFrom(from)) return false;
        theMailUtil.setNamePass(username,password);

        if(!theMailUtil.sendOut()) return false;
        return true;
    }


    /**
     * 发送邮件,含附件
     * @param to
     * @param subject
     * @param content
     * @param filename
     * @return
     */
    public static boolean send(String to,String subject,String content,String filename) {
//        MailUtil theMailUtil = new MailUtil(SkxxConfig.get("MAIL_SMTP"));
//        theMailUtil.setNeedAuth(true); //需要验证
//
//        if(!theMailUtil.setSubject(subject)) return false;
//        if(!theMailUtil.setBody(content)) return false;
//        if(filename!=null) {
//            if (!theMailUtil.addFileAffix(filename)) return false;
//        }
//        if(!theMailUtil.setTo(to)) return false;
//        if(!theMailUtil.setFrom(SkxxConfig.get("MAIL_FROM"))) return false;
//        theMailUtil.setNamePass(SkxxConfig.get("MAIL_USERNAME"),SkxxConfig.get("MAIL_PASSWORD"));
//
//        if(!theMailUtil.sendOut()) return false;
        return true;
    }

    public static void main(String[] args){
        String smtp = "smtp.qq.com";//qq邮箱使用这个,类似,163邮箱使用 smtp.163.com
        String from = "1349370365@qq.com";//发件人
        String to = "5311761@qq.com";//收件人
        String copyto = "1439867623@qq.com";//抄送人
        String subject = "YOUJZT";//主题
        String content = "<p>云密码机告警:</p>\n" +
                "<p>&nbsp; &nbsp; &nbsp; &nbsp;{warnInfo}</p>\n" +
                "<p>&nbsp; &nbsp; &nbsp; &nbsp;如有问题请联系***</p>\n" +
                "<p>大数据中心</p>";//内容
        String username="1349370365@qq.com";//你的邮箱
        String password="wzkhzehehwyfjjbe";//密码
//        String filename = "d:\\about.html";

        String html = content.replace("{warnInfo}", "----------");
        MailUtil.send(smtp, from, to,subject, html, username, password);

    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值