带有附件的邮件发送功能

邮件发送功能需要使用到的包是javax.mail,版本号应该无所谓,都差不多。我所用的是1.5.0-b01版本。

        <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>mail</artifactId>
            <version>1.5.0-b01</version>
        </dependency>

具体的代码如下:

邮件发送功能的代码

package com.example.javaemail;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;


public class EmailSender {
    // 发件人的 邮箱 和 密码
    public static String SEND_EMAIL_ACCOUNT = "123@163.com";
    public static String SEND_EMAIL_PASSWORD = "123456";

    // 发件人邮箱的 SMTP 服务器地址, 必须准确, 不同邮件服务器地址不同
    //在公司中进行开发时,需要与业务或项目经理确认smtp的服务器地址,
    // 公司邮箱的smtp地址与我们常用的邮箱smtp地址可能完全不同
    public static String SMTP_HOST = "smtp.163.com";
    //邮箱的smtp服务器端口,这里是开启ssl加密后的smtp服务器端口号
    public static String SMTP_PORT = "465";
    //开通smtp服务时有的邮箱会有授权码
    public static String AUTHORIZATION_CODE = "123abc";

    //在配置properties时使用到以下变量,固定不可变。
    public static String MAIL_TRANSPORT_PROTOCAL = "mail.transport.protocol";
    public static String MAIL_SMTP_HOST = "mail.smtp.host";
    public static String MAIL_SMTP_AUTH = "mail.smtp.auth";
    public static String MAIL_SMTP_PORT = "mail.smtp.port";

    public void sendEmail() {
        //邮箱的一些配置信息
        Properties properties = getProperties();
        //获取session,这里的session是javax包中的,注意不要导错包
        Session session = getSession(properties);
        //这里是设置要做为附件发送的文件的路径
        String inputFilePath = "F:/test.pdf";
        //创建邮件信息
        MimeMessage message = createMessage(session, inputFilePath);

        Transport transport = null;
        try {
            transport = session.getTransport();
            transport.connect(SEND_EMAIL_ACCOUNT, SEND_EMAIL_PASSWORD);
            transport.sendMessage(message, message.getAllRecipients());
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        } finally {
            try {
                if (transport != null)
                    transport.close();
            } catch (MessagingException e) {
                e.printStackTrace();
            }
        }
    }

    private MimeMessage createMessage(Session session, String inputFilePath) {
        MimeMessage message = new MimeMessage(session);

        try {
            //设置发件人邮箱地址、名称、编码格式
            message.setFrom(new InternetAddress(SEND_EMAIL_ACCOUNT, SEND_EMAIL_ACCOUNT.substring(0, SEND_EMAIL_ACCOUNT.indexOf("@")), "utf-8"));
            //设置收件人邮箱地址、名称、编码格式,可设置多个收件人邮箱
            message.setRecipients(MimeMessage.RecipientType.TO, new InternetAddress[]{new InternetAddress("987@163.com", "收件人名称", "utf-8")});

            message.setSubject("邮件主题");
            message.setSentDate(new Date());
            MimeMultipart messageMultipart = new MimeMultipart("mixed");
            message.setContent(messageMultipart);

            //邮件正文
            MimeBodyPart content = new MimeBodyPart();
            MimeMultipart contentMultipart = new MimeMultipart("related");
            MimeBodyPart body = new MimeBodyPart();
            body.setContent("此处是邮件正文", "text/html;charset=utf-8");
            contentMultipart.addBodyPart(body);
            content.setContent(contentMultipart);
            messageMultipart.addBodyPart(content);

            //邮件附件
            MimeBodyPart attachment = new MimeBodyPart();
            DataSource dataSource = new FileDataSource(new File(inputFilePath));
            DataHandler dataHandler = new DataHandler(dataSource);
            attachment.setDataHandler(dataHandler);
            attachment.setFileName("abc.pdf");
            messageMultipart.addBodyPart(attachment);

            message.saveChanges();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        return message;
    }

    private Session getSession(Properties properties) {
        return Session.getInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(SEND_EMAIL_ACCOUNT, AUTHORIZATION_CODE);
            }
        });
    }

    private Properties getProperties() {
        // 创建参数配置, 用于连接邮件服务器的参数配置
        Properties props = new Properties();                    // 参数配置
        props.setProperty(MAIL_TRANSPORT_PROTOCAL, "smtp");   // 使用的协议(JavaMail规范要求)
        props.setProperty(MAIL_SMTP_HOST, SMTP_HOST);   // 发件人的邮箱的 SMTP 服务器地址
        props.setProperty(MAIL_SMTP_AUTH, "true");            // 需要请求认证

        props.setProperty(MAIL_SMTP_PORT, SMTP_PORT);
        //邮箱使用ssl加密时需要以下代码,同时要使用对应的端口号,如163邮箱开启ssl加密后端口号为465。但是有的邮箱不需加密,或是报错,可将这三行代码注释掉。
        props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.setProperty("mail.smtp.socketFactory.fallback", "false");
        props.setProperty("mail.smtp.socketFactory.port", SMTP_PORT);

        return props;
    }
}

测试类代码

public class EmailTest {
    public static void main(String[] args) {
        EmailSender sender = new EmailSender();
        sender.sendEmail();
    }
}

附件名称中文时可能出现乱码,以下代码可以解决乱码问题。

 sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
//fileName为文件名,字符串格式
 attachment.setFileName("=?GBK?B?"+enc.encode(fileName.getBytes())+"?=");

注意:

  1. 邮件发送功能的方法也可以写成静态的;
  2. 会产生一些异常,比如Unrecognized SSL message, plaintext connection?这需要检查端口号,在开启SSL加密后端口号会改变,可以上网上搜索,一般的可以使用465试试看;
  3. 会产生一些异常,比如 sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target。这种在网上说是证书问题,我也产生过这种异常可能是网络问题,公司的网络有限制(百度都没有办法使用,说百度证书有问题。。。),后来我连接的自己的手机热点,就没有这个异常了。
  4. 邮箱的参数,可以写在配置文件中,也可以写在数据库中。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值