Java实现邮件发送

开启 POP/SMTP 服务,通常在设置中进行设置。

Java实现邮件发送_第1张图片

这是企业邮箱

pom.xml


    javax.mail
    mail
    1.4.7

发送带附件的邮件

package com.xh.test;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.UnsupportedEncodingException;
import java.util.Properties;

/**
 * @author H.Yang
 * @date 2023/2/3
 */
public class AppDemo {

    /**
     * 发送人
     */
    private final static String SEND_MAIL = "[email protected]";
    /**
     * 接收人
     */
    private final static String RECEIVE_MAILS[] = {"[email protected]"};
    /**
     * 抄送人
     */
    private final static String CC_MAILS[] = {"[email protected]"};
    /**
     * 发送人密码
     */
    private final static String PASSWORD = "xxxxx";

    /**
     * 创建session
     *
     * @return
     */
    private static Session createSession() {
        Properties props = new Properties();
        //使用的协议(JavaMail规范要求)
        props.setProperty("mail.transport.protocol", "smtp");
        //发件人的邮箱的 SMTP 服务器地址
        props.setProperty("mail.smtp.host", "smtp.exmail.qq.com");
        // 是否需要请求认证
        props.setProperty("mail.smtp.auth", "true");
        // 启用TLS加密
        props.setProperty("mail.smtp.starttls.enable", "true");

        //> SMTP 服务器的端口
        // 非 SSL 连接的端口一般默认为 25,可以不添加
        // 如果开启了 SSL 连接,需要改为对应邮箱的 SMTP 服务器的端口,具体可查看对应邮箱服务的帮助
        //
        // QQ邮箱的SMTP(SLL)端口为465或587
//        props.setProperty("mail.smtp.port", "465");
//        props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
//        props.setProperty("mail.smtp.socketFactory.fallback", "true");
//        props.setProperty("mail.smtp.socketFactory.port", "465");

        // 创建Session
        Session session = Session.getInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(SEND_MAIL, PASSWORD);
            }
        });

        // 开启调试模式
        session.setDebug(true);

        return session;
    }

    /**
     * 创建文本邮件对象
     *
     * @param session
     * @return
     * @throws Exception
     */
    public static MimeMessage createTextMessage(Session session) throws UnsupportedEncodingException, MessagingException {
        MimeMessage message = new MimeMessage(session);

        message.setFrom(new InternetAddress(SEND_MAIL, "测试文件邮件"));
        message.setRecipients(MimeMessage.RecipientType.TO, getInternetAddresses(RECEIVE_MAILS));
        message.setRecipients(MimeMessage.RecipientType.CC, getInternetAddresses(CC_MAILS));
        message.setSubject("文件邮件");

        message.setContent("您好,我是研发。", "text/html;charset=UTF-8");
        message.saveChanges();

        return message;
    }


    /**
     * 创建附件邮件对象
     *
     * @param session
     * @return
     * @throws Exception
     */
    public static MimeMessage createattachmentMessage(Session session) throws UnsupportedEncodingException, MessagingException {
        MimeMessage message = new MimeMessage(session);

        message.setFrom(new InternetAddress(SEND_MAIL, "测试带附件的邮件"));
        message.setRecipients(MimeMessage.RecipientType.TO, getInternetAddresses(RECEIVE_MAILS));
        message.setRecipients(MimeMessage.RecipientType.CC, getInternetAddresses(CC_MAILS));
        message.setSubject("带附件的邮件");

        // 正文
        MimeBodyPart contentText = new MimeBodyPart();
        contentText.setContent("发送内容信息", "text/html;charset=utf-8");

        // 附件
        DataHandler dataHandler = new DataHandler(new FileDataSource("C:\\Users\\Andrew\\桌面\\asdfghjkl.xls"));
        MimeBodyPart filepart = new MimeBodyPart();
        filepart.setDataHandler(dataHandler);
        filepart.setFileName(MimeUtility.encodeText(dataHandler.getName()));

        // 拼接
        MimeMultipart mimeMultipart = new MimeMultipart();
        mimeMultipart.addBodyPart(filepart);//附件
        mimeMultipart.addBodyPart(contentText);//正文
        mimeMultipart.setSubType("mixed"); //正文和附件都存在邮件中,所有类型设置为mixed

        message.setContent(mimeMultipart);
        message.saveChanges();

        return message;
    }

    private static InternetAddress[] getInternetAddresses(String[] arrs) throws AddressException {
        InternetAddress[] sendTo = new InternetAddress[arrs.length];
        for (int i = 0; i < arrs.length; i++) {
            sendTo[i] = new InternetAddress(arrs[i]);

        }
        return sendTo;
    }


    public static void main(String[] args) throws MessagingException {
        Session session = createSession();

        Transport transport = null;
        try {
            MimeMessage mimeMessage = createTextMessage(session);

            // 根据 Session 获取邮件传输对象
            transport = session.getTransport();

            // 使用邮箱账号和密码连接邮件服务器, 这里认证的邮箱必须与 message 中的发件人邮箱一致,否则报错
            transport.connect(SEND_MAIL, PASSWORD);
            transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());

            System.out.println("邮件发送成功!");
        } catch (MessagingException | UnsupportedEncodingException e) {
            e.printStackTrace();
        } finally {
            assert transport != null;
            transport.close();
        }


    }

}

你可能感兴趣的:(Java,java,邮件)