javaEmail发送邮件带附件发送

public class SendEmail {
    //服務器地址
    public static final String HOST ="smtp.163.com";
    public static final String PROTOCOL ="smtp";
    public static final int PORT = 465;
    public static final String FROM ="*****@163.com";
    public static final String PWD ="*****";//授权码

    /**
     * 获取Session
     *
     * @return
     */
    private static Session getSession() {
        Properties props = new Properties();
        props.put("mail.smtp.host", HOST);//设置服务器地址
        props.put("mail.store.protocol", PROTOCOL);//设置协议
        props.put("mail.smtp.port", PORT);//设置端口
        props.put("mail.smtp.auth", true);
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.setProperty("mail.debug", "true");
        props.setProperty("mail.smtp.auth", "true");


        //邮件服务登录认证
        Authenticator authenticator = new Authenticator() {

            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                //FROM是公司郵件地址,PWD是授權碼
                return new PasswordAuthentication(FROM, PWD);
            }

        };
        Session session = Session.getInstance(props, authenticator);
        return session;
    }

    /**
     * @param title
     * @param toEmail
     * @param content
     * @param cc 抄送, 多个Email以英文逗号分隔
     * @param filePath 附件地址
     */
    public static void sendEmail(String title, String toEmail, String content,String cc,String filePath) {
        Session session = getSession();

        try {
//            System.out.println("--send--" + content);
            Message msg = new MimeMessage(session);
            MimeMultipart multipart = new MimeMultipart();
            try {
                msg.setSubject(MimeUtility.encodeText(title, MimeUtility.mimeCharset("utf-8"), null));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            msg.setContent(content, "text/html;charset=UTF-8");
            msg.setSentDate(new Date());
            Address from = new InternetAddress(FROM);//发送人
            msg.setFrom(from);
            Address to = new InternetAddress(toEmail);//接收人
            msg.setRecipient(Message.RecipientType.TO, to);
            // 设置抄送人
            if (cc != null && cc.length() > 0) {
                msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc));
            }

            // 添加邮件正文
            BodyPart contentBodyPart = new MimeBodyPart();
            // 邮件内容
            contentBodyPart.setContent(content, "text/html;charset=UTF-8");
            multipart.addBodyPart(contentBodyPart);

            // 添加附件

            if (filePath != null && !"".equals(filePath)) {
                //BodyPart attachmentBodyPart = new MimeBodyPart();
                //                // 根据附件路径获取文件,
                //FileDataSource dataSource = new FileDataSource(filePath);

                contentBodyPart = new MimeBodyPart();
                FileDataSource dataSource = new FileDataSource(filePath);
                contentBodyPart.setDataHandler(new DataHandler(dataSource));
                //MimeUtility.encodeWord可以避免文件名乱码
                contentBodyPart.setFileName(MimeUtility.encodeWord(dataSource.getFile().getName()));
                //
                multipart.addBodyPart(contentBodyPart);
            }


            // 邮件的文本内容
            msg.setContent(multipart);

            // 4. 发送邮件,Transport每次发送成功程序帮忙关闭
            Transport.send(msg, msg.getAllRecipients());



            /*  // 设置正文
            BodyPart bp = new MimeBodyPart();
            // 设置附件
            if (zz != null && !"".equals(zz)) {

                    bp = new MimeBodyPart();
                    FileDataSource fds = new FileDataSource(zz);
                    bp.setDataHandler(new DataHandler(fds));
                    bp.setFileName(MimeUtility.encodeText(fds.getName(), "UTF-8", "B"));
                    mp.addBodyPart(bp);

            }
              Transport.send(msg);*/
        } catch (MessagingException mex) {
            mex.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }




    /**
     * 附件发送,待测试
     *
     * @param filePath 附件地址
     * @param title    标题
     * @param toEmail  发送给
     */

    public static void sendEmailWithMultipart( String title, String toEmail, String content,String cc,String filePath) {

            Session session = getSession();
            // 开启Session的debug模式,这样就可以查看到程序发送Email的运行状态
            session.setDebug(true);
        try {
            // 3. 创建邮件
            // 创建邮件对象
            Message msg = new MimeMessage(session);
            // 向multipart对象中添加邮件的各个部分内容,包括文本内容和附件
            Multipart multipart = new MimeMultipart();
            //新添加
            try {
                msg.setSubject(MimeUtility.encodeText(title, MimeUtility.mimeCharset("utf-8"), null));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            // 邮件的标题
            msg.setSubject(title);

            // 邮件发送日期
            msg.setSentDate(new Date());
            // 指明邮件的发件人
            msg.setContent(content, "text/html;charset=UTF-8");
            msg.setSentDate(new Date());
            Address from = new InternetAddress(FROM);//发送人
            msg.setFrom(from);
            Address to = new InternetAddress(toEmail);//接收人
            // 指明邮件的收件人
            msg.setRecipient(Message.RecipientType.TO, to);


            // 指明邮件的抄送人
            if (cc != null && cc.length() > 0) {
                msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc));
            }
           // message.setRecipient(Message.RecipientType.CC, from);



            // 添加邮件正文
            BodyPart contentBodyPart = new MimeBodyPart();
            // 邮件内容
            contentBodyPart.setContent(content, "text/html;charset=UTF-8");
            multipart.addBodyPart(contentBodyPart);

            // 添加附件
            if (filePath != null && !"".equals(filePath)) {
                BodyPart attachmentBodyPart = new MimeBodyPart();
                // 根据附件路径获取文件,
                FileDataSource dataSource = new FileDataSource(filePath);
                attachmentBodyPart.setDataHandler(new DataHandler(dataSource));
                //MimeUtility.encodeWord可以避免文件名乱码
                attachmentBodyPart.setFileName(MimeUtility.encodeWord(dataSource.getFile().getName()));
                multipart.addBodyPart(attachmentBodyPart);
            }
            // 邮件的文本内容
            msg.setContent(multipart);

            // 4. 发送邮件,Transport每次发送成功程序帮忙关闭
            Transport.send(msg, msg.getAllRecipients());
        } catch (MessagingException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值