纯java发送邮件详解(163、qq等)

邮件发送,亲测有效

邮件发送关键点

1.开通SMTP客户端服务(必须开通,不开通无法使用)

  • 163开通:
    这里写图片描述
    163开通时,手动设置授权码,请牢记

  • qq开通:
    这里写图片描述
    qq开通后自动生成秘钥,请牢记
    比如
    得到密钥:QKBE KQQW UDVC BJAB
    实际使用密钥时:qkbekqqwudvcbjab

2.server,port 书写

  • 163发送:

server= “smtp.163.com”
port= “465”

SSL端口”465”,”994”都可以
非SSL端口 “25”

  • qq发送:
    server= “smtp.qq.com”
    port= “465”

SSL端口”465”,”537”都可以
非SSL端口 “25”

3.username、password
注意:username为用户名,password为开通AMTP提供的秘钥(授权码),并不是QQ密码
qq :若修改qq密码,秘钥无效,需重新获取秘钥

代码分析

  • 1.MimeMessage 邮件
            MimeMessage message = new MimeMessage(session);
  • 2.subject 主题
            message.setSubject("发送邮件测试", "charset=utf-8");
  • 3.MimeMultipart 整封邮件的MINE消息体
            MimeMultipart multipart = new MimeMultipart();
  • 4.MimeBodyPart 内容(可以多个)
            MimeBodyPart hPart = new MimeBodyPart();
            hPart.setContent("html代码","text/html;charset=utf-8");
            hPart.setContent("文本内容");
  • 5.将内容set进MINE消息体,将消息体set进邮件
            multipart.addBodyPart(hPart);
            message.setContent(multipart);
  • 6.attachment 附件数组

    将附件一层层遍历,拿到每个附件,添加到内容中


            // String attachment [] = new String[]{"C:/Users/study.txt","C:/Users/receipt_sample.pdf"};
            //附件的遍历
            if(attachment != null && attachment.length != 0) {  
                File file =null;
                for(int i=0;i<attachment.length;i++) {
                    MimeBodyPart attachment_part = new MimeBodyPart();
                    file = new File(attachment[i]);
                    attachment_part.attachFile(file);
                    attachment_part.setFileName(MimeUtility.encodeText(file.getName()));//设置附件名字
                    multipart.addBodyPart(attachment_part);
                }
                System.out.println("文件个数:"+attachment.length);
            }
  • 7.form 发件人
            String sender = "test@rst.ricoh.com";
            // set from 设置发件人
            try {
                message.setFrom(new InternetAddress(sender));
            } catch (MessagingException e){
                System.out.println("Create Mail: " + e.getMessage() + " Try Default Sender.");
            }
  • 7.To收件人
            String[] to = new String[]{"toa@rst.ricoh.com","tob@rst.ricoh.com"}; //收件人
            // set to 设置收件人(可以多个收件人)
            InternetAddress[] to_list = new InternetAddress[to.length];
            for(int i = 0; i < to_list.length; ++i)
            {
                to_list[i] = new InternetAddress(to[i]);
                to_list[i].validate();
            }
            message.setRecipients(RecipientType.TO, to_list);

综合:认证setAuthentication()、环境getSession()、邮件地址合法isEmailValid()等函数在全部代码中,需要请查看
全部代码

package cn.zbj.email;

import java.io.File;
import java.io.IOException;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;


public class Email {
    private final String SMTP_TIMEOUT = "15000";        // in million seconds

    String server;
    String port;

    public enum SSL_TYPE {
        NONE,
        TLS,
        SSL,
        ;
    }
    SSL_TYPE ssl;

    private final String CHARSET = "utf-8";

    Authenticator authenticator = null;

    public Email(String smtpServer, String smtpPort, SSL_TYPE sslType)
    {
        server = smtpServer;
        port = smtpPort;
        ssl = sslType;
    }

    public void setAuthentication(final String username, final String password)
    {
        if(username == null || username.isEmpty())
        {
            return;
        }
        authenticator = new Authenticator(){

            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }

        };
    }
    public boolean send(String sender, String[] to, String subject, String text, String[] attachment)
    {
        //环境
        Session session = getSession();
        if(session == null)
        {
            return false;
        }

        Message mail = createMail(session, sender, to, subject, text, attachment);
        if(mail == null)
        {
            return false;
        }
        boolean isSuccess = false;
        try {
            //发送邮件
            Transport.send(mail);
            isSuccess = true;
        } catch (MessagingException e) {
            e.getMessage();
        }
        return isSuccess;
    }



    public boolean checkConnection()
    {
        Session session = getSession();
        if(checkConnection(session))
        {
            return true;
        }
        return false;
    }

    private boolean checkConnection(Session session)
    {
        if(session == null)
        {
            return false;
        }
        boolean isSuccess = false;
        try {
            Transport transport = session.getTransport("smtp");
            transport.connect();
            transport.close();
            isSuccess = true;
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        return isSuccess;
    }

    private Session getSession()
    {
        Properties properties = new Properties();
        properties.setProperty("mail.smtp.host", server);
        properties.setProperty("mail.smtp.port", port);
        properties.setProperty("mail.smtp.connectiontimeout", SMTP_TIMEOUT);
        properties.setProperty("mail.smtp.timeout", SMTP_TIMEOUT);

        switch(ssl)
        {
        case SSL:
            properties.setProperty("mail.smtp.ssl.enable", "true");
            properties.setProperty("mail.smtp.socketFactory.port", port);
            properties.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            properties.setProperty("mail.smtp.socketFactory.fallback", "false");
            properties.setProperty("mail.smtp.ssl.trust", server);
            break;
        case TLS:
            properties.setProperty("mail.smtp.starttls.enable", "true");
            properties.setProperty("mail.smtp.ssl.trust", server);
            break;
        default:
            break;
        }

        Session session;
        if(authenticator != null)
        {
            properties.setProperty("mail.smtp.auth", "true");
            session = Session.getInstance(properties, authenticator);
        }
        else
        {
            session = Session.getInstance(properties);
        }
        //      session.setDebug(true);

        return session;
    }

    private Message createMail(Session session, String sender, String[] to, String subject, String text, String[] attachment)
    {
        if(session == null)
        {
            return null;
        }
        //邮件
        MimeMessage message = null;
        try {
            message = new MimeMessage(session);
            // set subject 设置主题
            message.setSubject(subject, CHARSET);

            // MimeMultipart 整封邮件的MINE消息体
            MimeMultipart multipart = new MimeMultipart();
            // MimeBodyPart 内容(允许多个,如正文,附件等)
            MimeBodyPart hPart = new MimeBodyPart();
            //设置html内容
            /*hPart.setContent(text,"text/html;charset=utf-8");*/
            //设置文本
            hPart.setText(text + "\n", CHARSET);    // append \n so that attachment will be add to next line, if any
            //将内容加入MINE消息体中
            multipart.addBodyPart(hPart);


            //附件的遍历
            if(attachment != null && attachment.length != 0) {  
                File file =null;
                for(int i=0;i<attachment.length;i++) {
                    MimeBodyPart attachment_part = new MimeBodyPart();
                    file = new File(attachment[i]);
                    attachment_part.attachFile(file);
                    attachment_part.setFileName(MimeUtility.encodeText(file.getName()));
                    multipart.addBodyPart(attachment_part);
                }
                System.out.println("文件个数:"+attachment.length);
            }

            //设置邮件的MINE消息体(把消息体加入邮件中)
            message.setContent(multipart);

            // set from 设置发件人
            try {
                message.setFrom(new InternetAddress(sender));
            } catch (MessagingException e){
                System.out.println("Create Mail: " + e.getMessage() + " Try Default Sender.");
            }


            // set to 设置收件人(可以多个收件人)
            InternetAddress[] to_list = new InternetAddress[to.length];
            for(int i = 0; i < to_list.length; ++i)
            {
                to_list[i] = new InternetAddress(to[i]);
                to_list[i].validate();
            }
            message.setRecipients(RecipientType.TO, to_list);

        } catch (MessagingException e) {
            message = null;
            System.out.println("Create Mail Fail: " + e.getMessage());
        }
        catch (IOException e)
        {
            message = null;
            System.out.println("Create Mail Fail: " + e.getMessage());
        }
        return message;
    }

    public static boolean isEmailValid(String email) {
        boolean isValid = false;
        try {
            InternetAddress address = new InternetAddress(email);
            address.validate();
            isValid = true;
        } catch (AddressException e) {
            // invalid email address
        }
        return isValid;
    }

    public static void main(String[] args) {


        //发件人邮箱的SMTP服务
        String server = "smtp.163.com";
        //端口号
        String port = "465";
        //使用的协议
        SSL_TYPE ssl = SSL_TYPE.TLS;


        //发件人邮箱用户名,SMTP(秘钥)授权码
        String username = "*@163.com";
        String password = "***";

        Email helper = new Email(server, port, ssl);
        //用户名密码验证
        helper.setAuthentication(username, password);
        //sender 发件人
        String sender = "test@rst.ricoh.com";
        //to 收件人
        String[] to = new String[]{"testa@rst.ricoh.com"}; //收件人
        //邮件标题
        String subject = "test from admin tool";
        //邮件内容
        //传文本
        String text = "test text";
        //传html代码
        //String text = "<span style='color:red'>内容</span><img src='http://img.zcool.cn/community/0117e2571b8b246ac72538120dd8a4.jpg@1280w_1l_2o_100sh.jpg'/>";

        //附件地址
        String filename[] = new String[]{"C:/study.txt","C:/receipt_sample.pdf"};
        // 发送邮件
        helper.send(sender, to, subject, text, filename);

        // 检查邮箱服务器连接
        boolean result = helper.checkConnection();
        System.out.println("connect: "+result);

        // 检查邮件是否可用
        boolean result2 = Email.isEmailValid("*@163.com");
    }


}

需要mail.jar请自行下载

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值