JAVA利用网易邮箱smtp服务发送邮件(使用465和25端口)

一、用465端口进行发送

	
			javax.mail
			mail
			1.4.1
		
MailUtil.java
package com.qiaojun;

import org.apache.commons.lang.StringUtils;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

/**
 * 用465端口发送邮件
 *
 * @author qiaojun
 * @date 2019/8/12
 */
public class MailUtil {

    private static String USER_NAME = "[email protected]";//发件人

    private static String PASSWORD = "xxxx";//密码

    private static String HOST = "smtp.ym.163.com";

    public static void main(String[] args) {
        sendMail("[email protected]", null, "测试标题", "测试内容");
    }

    public static void sendMail(String subject, String content) {
        sendMail(null, null, subject, "content");
    }

    public static void sendMail(String to, String subject, String content) {
        sendMail(to, null, subject, "content");
    }

    /**
     * 发邮件端口改为465
     *
     * @param to      发送人 逗号分开
     * @param cc      抄送人 逗号分开
     * @param content 发送内容
     */
    public static void sendMail(String to, String cc, String subject, String content) {
        if (null == to) {
            return;
        }
        Properties props = new Properties();
        props.put("username", USER_NAME);
        props.put("password", PASSWORD);

        //网易的smtp服务器地址
        props.put("mail.smtp.host", HOST);
        //SSLSocketFactory类的端口
        props.put("mail.smtp.socketFactory.port", "465");
        //SSLSocketFactory类
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.auth", "true");
        //网易提供的ssl加密端口,QQ邮箱也是该端口
        props.put("mail.smtp.port", "465");

        Session defaultInstance = Session.getDefaultInstance(props);
        try {
            Session session = Session.getInstance(props, null);
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(props.getProperty("username")));
            if (StringUtils.isEmpty(to)) {
                to = "[email protected]";
            }
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
            if (cc != null) {
                message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc));
            }
            message.setSubject(subject);
            // 正文和响应头
            message.setContent(content, "text/html;charset=UTF-8");
            message.saveChanges();
            Transport transport = defaultInstance.getTransport("smtp");
            transport.connect(props.getProperty("mail.smtp.host"), props.getProperty("username"), props.getProperty("password"));
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }
}

 

二、使用默认的25端口发送

   
            javax.mail
            mail
            1.4.1
        
        
            org.springframework
            spring-context-support
            4.3.18.RELEASE
        
MailUtl.java
package com.jmt.alipay.util;


import org.springframework.core.io.ClassPathResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

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

/**
 * 邮件发送工具类
 * @author qiaojun
 * @date 2019/5/21
 */
public class MailUtl {

    private static JavaMailSenderImpl mailSender = null;

    /**
     * 发送邮件客户端配置
     */
    private static final String USER_NAME = "[email protected]";//发件人
    private static final String PASSWORD = "xxxxx";//密码
    private static final String HOST = "smtp.ym.163.com";
    private static final int PORT = 25;

    private synchronized static JavaMailSenderImpl getSender()
    {
        if (null == mailSender)
        {
            mailSender = new JavaMailSenderImpl();
            mailSender.setHost(HOST);
            mailSender.setUsername(USER_NAME);
            mailSender.setPort(PORT);
            mailSender.setPassword(PASSWORD);
            Properties props = new Properties();
            props.setProperty("mail.smtp.auth", "true");
            mailSender.setJavaMailProperties(props);
        }
        return mailSender;
    }

    /**
     * 发送普通邮件
     * @param subject 标题
     * @param content 内容
     * @param to 收件人
     * @param cc 抄送
     */
    public static void sendSimpleMail(String subject, String content,String[] to,String[] cc)
    {
        SimpleMailMessage msg = new SimpleMailMessage();
        msg.setSubject(subject);
        msg.setText(content);
        msg.setFrom(USER_NAME);
        if(null != to){
            msg.setTo(to);
        }else {
            msg.setTo(new String[]{"[email protected]"});
        }
        if(null != cc){
            msg.setCc(cc);
        }
        getSender().send(msg);
    }

    /**
     * 发送带附件的邮件
     * @param subject 标题
     * @param content 内容
     * @param to 收件人
     * @param cc 抄送
     * @param filePath 附件(文件)路径
     */
    public static void sendAttachMail(String subject, String content,String[] to,String[] cc,String filePath)
    {
        // 使用JavaMail的MimeMessage,支持更加复杂的邮件格式和内容
        MimeMessage msg = getSender().createMimeMessage();
        // 加入附件
        try
        {
            // 创建MimeMessageHelper对象,处理MimeMessage的辅助类
            MimeMessageHelper helper = new MimeMessageHelper(msg, true);
            // 使用辅助类MimeMessage设定参数
            helper.setFrom(USER_NAME);
            helper.setTo(to);
            helper.setCc(cc);
            helper.setSubject(subject);
            helper.setText(content);
            // 加载文件资源,作为附件
            ClassPathResource file = new ClassPathResource(filePath);
            helper.addAttachment("attachment", file);
        }
        catch (MessagingException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // 发送邮件
        getSender().send(msg);
    }

    /**
     * 发送Html格式邮件
     * @param subject 标题
     * @param content 内容
     * @param to 收件人
     * @param cc 抄送
     */
    public static void sendHtmlMail(String subject, String content,String[] to,String[] cc)
    {
        // 使用JavaMail的MimeMessage,支持更加复杂的邮件格式和内容
        MimeMessage msg = getSender().createMimeMessage();
        try
        {
            // 创建MimeMessageHelper对象,处理MimeMessage的辅助类,参数true可输出html格式,gbk编码格式
            MimeMessageHelper helper = new MimeMessageHelper(msg, true, "GBK");

            helper.setFrom(USER_NAME);
            helper.setTo(to);
            helper.setCc(cc);
            helper.setSubject(subject);
            helper.setText(content, true);
        }
        catch (MessagingException e)
        {
            e.printStackTrace();
        }
        getSender().send(msg);

    }

    /**
     * 用ssl用456端口发送邮件
     * 发送邮件(灵活度高,通用版)
     * @param to 收件人, 多个Email以英文逗号分隔
     * @param cc 抄送, 多个Email以英文逗号分隔
     * @param subject 主题
     * @param content 内容
     * @param fileList 附件列表
     * @return
     */
    public static boolean sendMail(String to, String cc, String subject, String content, String[] fileList){
        try {
            Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
            final String sslFactory = "javax.net.ssl.SSLSocketFactory";
            final Properties p = System.getProperties() ;
            p.setProperty("mail.smtp.host", HOST);
            p.setProperty("mail.smtp.auth", "true");
            p.setProperty("mail.smtp.user", USER_NAME);
            p.setProperty("mail.smtp.pass", PASSWORD);

            p.setProperty("mail.smtp.socketFactory.class", sslFactory);
            p.setProperty("mail.smtp.socketFactory.fallback", "false");
            //邮箱发送服务器端口,这里设置为465端口
            p.setProperty("mail.smtp.port", "465");
            p.setProperty("mail.smtp.socketFactory.port", "465");

            // 根据邮件会话属性和密码验证器构造一个发送邮件的session
            Session session = Session.getInstance(p, new Authenticator(){
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(p.getProperty("mail.smtp.user"),p.getProperty("mail.smtp.pass"));
                }
            });
            session.setDebug(true);
            Message message = new MimeMessage(session);
            //消息发送的主题
            message.setSubject(subject);
            //接受消息的人
//            message.setReplyTo(InternetAddress.parse(FROM_MAIL_NAME));
            //消息的发送者
            message.setFrom(new InternetAddress(p.getProperty("mail.smtp.user"),"参数"));
            // 创建邮件的接收者地址,并设置到邮件消息中
            String[] split = to.split(",");
            InternetAddress []tos = new InternetAddress[split.length];
            for (int i = 0; i < split.length; i++) {
                tos[i]=new InternetAddress(split[i]);
            }
            // 设置抄送人
            if (cc != null && cc.length() > 0) {
                message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc));
            }
            message.setRecipients(Message.RecipientType.TO, tos);
            // 消息发送的时间
            message.setSentDate(new Date());
            Multipart mainPart = new MimeMultipart();
            // 创建一个包含HTML内容的MimeBodyPart
            BodyPart html = new MimeBodyPart();
            // 设置HTML内容
            html.setContent(content, "text/html; charset=utf-8");
            mainPart.addBodyPart(html);
            // 将MiniMultipart对象设置为邮件内容
            message.setContent(mainPart);
            // 设置附件
            if (fileList != null && fileList.length > 0) {
                for (String aFileList : fileList) {
                    html = new MimeBodyPart();
                    FileDataSource fds = new FileDataSource(aFileList);
                    html.setDataHandler(new DataHandler(fds));
                    html.setFileName(MimeUtility.encodeText(fds.getName(), "UTF-8", "B"));
                    mainPart.addBodyPart(html);
                }
            }
            message.setContent(mainPart);
            message.saveChanges();
            Transport.send(message);
        } catch (MessagingException | UnsupportedEncodingException  e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public static void main(String[] args) {
        String[] str = {"[email protected]"};//收件人
        String[] strcs = {"[email protected]"};//抄送人
        sendSimpleMail("测试标题","测试内容",null,null);
//        sendMail("[email protected]",null,"标题","内容",null);
    }
}

 

你可能感兴趣的:(JAVA利用网易邮箱smtp服务发送邮件(使用465和25端口))