java发送邮件

   java代码发送邮件实例以qq邮箱为例

一、邮箱设置

      qq邮件账户设置里要打开这个,打开的时候会获得一个16位的邮件授权码(需要短信认证)

 二、依赖的包pom.xml

<!--发送邮件需要的依赖-->
        <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>mail</artifactId>
            <version>1.4.7</version>
        </dependency>

三、代码

package com.example.demo.mail;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
import com.sun.mail.util.MailSSLSocketFactory;
import javax.mail.*;
import javax.mail.internet.MimeMultipart;
import java.security.GeneralSecurityException;


public class SendEmail {

    //邮件发送主方法
    public static void main(String[] args)  {

        try {
            //不带附件的邮件发送
            simpleSend("smtp.qq.com","896xx173@qq.com","fsfxxxxxxxxxxhbe","yangxxxx@163.com","Hello Mail",
                    "我的想法是把代码放进一个循环里");
        } catch (MessagingException e) {
            e.printStackTrace();
        } catch (GeneralSecurityException e) {
            e.printStackTrace();
        }

        try {
            //带附件的邮件发送
            complexEmail("smtp.qq.com","896xx173@qq.com","fsfxxxxxxxxxxhbe","yangxxxx@163.com","带图片和附件的邮件",
                    "带附件的邮件","E:\\1.jpg","2.jpg");
        } catch (MessagingException e) {
            e.printStackTrace();
        } catch (GeneralSecurityException e) {
            e.printStackTrace();
        }
    }

    /*
      发送没有附件的邮件
      smtpService:邮件服务器
      sendEmail:发送邮件
      password:邮件授权码
      receiveEmail:接收邮件地址
      emailTitle:邮件主题
      emailText:邮件内容
     */
    public static void simpleSend(String smtpService,String sendEmail,String password ,String receiveEmail,
                                  String emailTitle,String emailText) throws MessagingException, GeneralSecurityException{
        //创建一个配置文件并保存
        Properties properties = new Properties();
        properties.setProperty("mail.host",smtpService);
        properties.setProperty("mail.transport.protocol","smtp");
        properties.setProperty("mail.smtp.auth","true");
        //QQ存在一个特性设置SSL加密
        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        properties.put("mail.smtp.ssl.enable", "true");
        properties.put("mail.smtp.ssl.socketFactory", sf);
        //创建一个session对象
        Session session = Session.getDefaultInstance(properties, new Authenticator() {

        });
        //开启debug模式
        session.setDebug(true);
        //获取连接对象
        Transport transport = session.getTransport();
        //连接服务器
        transport.connect(smtpService,sendEmail,password);
        //创建邮件对象
        MimeMessage mimeMessage = new MimeMessage(session);
        //邮件发送人
        mimeMessage.setFrom(new InternetAddress(sendEmail));
        //邮件接收人
        mimeMessage.setRecipient(Message.RecipientType.TO,new InternetAddress(receiveEmail));
        //邮件标题
        mimeMessage.setSubject(emailTitle);
        //邮件内容
        mimeMessage.setContent(emailText,"text/html;charset=UTF-8");
        //发送邮件
        transport.sendMessage(mimeMessage,mimeMessage.getAllRecipients());
        //关闭连接
        transport.close();
    }



        /*
            带附件的邮件发送
            smtpService:邮件服务器
            sendEmail:发送邮件
            password:邮件授权码
            receiveEmail:接收邮件地址
            emailTitle:邮件主题
            emailText:邮件内容
         */
        public static void complexEmail( String smtpService,String sendEmail,String password ,String receiveEmail,
                                                String emailTitle,String emailText,String filePath,String fileName) throws MessagingException,
                GeneralSecurityException, MessagingException {

            Properties prop = new Properties();
            prop.setProperty("mail.host", smtpService);  //设置QQ邮件服务器
            prop.setProperty("mail.transport.protocol", "smtp"); // 邮件发送协议
            prop.setProperty("mail.smtp.auth", "true"); // 需要验证用户名密码

            // QQ邮箱设置SSL加密
            MailSSLSocketFactory sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
            prop.put("mail.smtp.ssl.enable", "true");
            prop.put("mail.smtp.ssl.socketFactory", sf);

            //1、创建定义整个应用程序所需的环境信息的 Session 对象
            Session session = Session.getDefaultInstance(prop, new Authenticator() {});

            //2、通过session获取transport对象
            Transport transport = session.getTransport();

            //3、通过transport对象邮箱用户名和授权码连接邮箱服务器
            transport.connect("smtp.qq.com",sendEmail,password);

            //4、创建邮件,传入session对象
            //消息的固定信息
            MimeMessage mimeMessage = new MimeMessage(session);
            //发件人
            mimeMessage.setFrom(new InternetAddress(sendEmail));
            //收件人
            mimeMessage.setRecipient(Message.RecipientType.TO,new InternetAddress(receiveEmail));
            //邮件标题
            mimeMessage.setSubject(emailTitle);

            //邮件内容
            MimeBodyPart mimeBody = new MimeBodyPart();
            DataHandler handler = new DataHandler(new FileDataSource(filePath));
            mimeBody.setDataHandler(handler);
            //准备文本
            MimeBodyPart text = new MimeBodyPart();
            //5,邮件内容
            text.setContent(emailText,"text/html;charset=utf-8");

            //拼装邮件正文
            MimeMultipart mimeMultipart = new MimeMultipart();
            mimeMultipart.addBodyPart(text);
            //将拼装好的正文内容设置为主体
            MimeBodyPart contentText = new MimeBodyPart();
            contentText.setContent(mimeMultipart);

            //附件
            MimeBodyPart appendix = new MimeBodyPart();
            appendix.setDataHandler(new DataHandler(new FileDataSource(filePath)));
            appendix.setFileName(fileName);

            //拼接附件
            MimeMultipart allFile = new MimeMultipart();
            allFile.addBodyPart(appendix);//附件 发送多个附件这里多加几个就ok
            allFile.addBodyPart(contentText);//正文
            allFile.setSubType("mixed"); //正文和附件都存在邮件中,所有类型设置为mixed

            //放到Message消息中
            mimeMessage.setContent(allFile);
            mimeMessage.saveChanges();//保存修改

            //5、发送邮件
            transport.sendMessage(mimeMessage,mimeMessage.getAllRecipients());

            //6、关闭连接
            transport.close();


        }


}
View Code

                                                                                 

 

posted @ 2021-06-28 18:09  万笑佛  阅读(93)  评论(0编辑  收藏  举报