【Java】使用JavaMail发送邮件以及开启ssl的使用总结

常见错误:

1.关于使用Java Mail进行邮件发送,抛出Could not connect to SMTP host: [email protected], port: 25的异常

2.使用 JavaMailSenderImpl SSL 465 发送邮件

3.java.net.SocketTimeoutException: Read timed out的解决办法

4.如何获取qq邮箱STMP授权码

加密与非加密配置方式

1.简单邮件非ssl使用25端口的STMP邮件

public class MailMessageSchedule {

    public void mailMessage()throws Exception {

        JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();
        System.setProperty("java.net.preferIPv4Stack", "true");
        //设定mail server
        senderImpl.setHost("smtp.qq.com");
        MimeMessage mailMessage = senderImpl.createMimeMessage();
        MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage,true,"utf-8");    messageHelper.addAttachment(fileName,file);
  
        //收件人
        messageHelper.setTo([email protected]);
        //发件人
        messageHelper.setFrom("[email protected]");
        //设置邮件标题
        messageHelper.setSubject(“标题”);
        //设置邮件内容,true表示开启HTML文本格式  
        messageHelper.setText(content,true);
        //这是发件人邮箱信息,username表示用户邮箱,password表示对应邮件授权码
        senderImpl.setUsername("[email protected]") ;
        senderImpl.setPassword("授权码") ;

        Properties prop = new Properties() ;
        prop.put("mail.smtp.auth", "true") ; // 将这个参数设为true,让服务器进行认证,认证用户名和密码是否正确
        prop.put("mail.smtp.timeout", "25000") ;
        senderImpl.setJavaMailProperties(prop);
        //发送邮件
        senderImpl.send(mailMessage);
        System.out.println("邮件发送成功..");

    }

}

2.加密邮件开启ssl使用465端口:

public class MailMessageSchedule {

    public void mailMessage()throws Exception {

        JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();
        System.setProperty("java.net.preferIPv4Stack", "true");
        //设定mail server
        senderImpl.setHost("smtp.qq.com");

        MimeMessage mailMessage = senderImpl.createMimeMessage();
        MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage,true,"utf-8");    messageHelper.addAttachment(fileName,file);
        
        //收件人
        messageHelper.setTo([email protected]);
        //发件人
        messageHelper.setFrom("[email protected]");
        //设置邮件标题
        messageHelper.setSubject(“标题”);
        //设置邮件内容,true表示开启HTML文本格式  
        messageHelper.setText(content,true);
        //这是发件人邮箱信息,username表示用户邮箱,password表示对应邮件授权码
        senderImpl.setUsername("[email protected]") ;
        senderImpl.setPassword("授权码") ;
        //开启ssl
        Properties properties = new Properties();
        properties.setProperty("mail.smtp.auth", "true");//开启认证
        properties.setProperty("mail.debug", "true");//启用调试
        properties.setProperty("mail.smtp.timeout", "200000");//设置链接超时
        properties.setProperty("mail.smtp.port", Integer.toString(25));//设置端口
        properties.setProperty("mail.smtp.socketFactory.port", Integer.toString(465));//设置ssl端口
        properties.setProperty("mail.smtp.socketFactory.fallback", "false");
        properties.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        senderImpl.setJavaMailProperties(properties);
        //发送邮件
        senderImpl.send(mailMessage);
        System.out.println("邮件发送成功..");

    }

}

代码示例

1.带附件的简单邮件:

package com.thon.task;

import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.Properties;

/**
 * @description 带附件邮件发送
 **/
public class FileMail {
    public static void main(String[] args) throws Exception{
        JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();

        //设定mail server
        senderImpl.setHost("smtp.qq.com");

        //建立邮件消息,发送简单邮件和html邮件的区别
        MimeMessage mailMessage = senderImpl.createMimeMessage();

        //注意这里的boolean,等于真的时候才能嵌套图片,在构建MimeMessageHelper时候,所给定的值是true表示启用,
        //multipart模式 为true时发送附件 可以设置html格式
        MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage,true,"utf-8");

        //设置收件人,寄件人
        messageHelper.setTo("[email protected]");
        messageHelper.setFrom("[email protected]");
        messageHelper.setSubject("测试邮件中上传附件!");

        //true 表示启动HTML格式的邮件
        messageHelper.setText("这是内容",true);

        FileSystemResource file = new FileSystemResource(new File("E:\\新建文件夹 (2)\\ysg.gif"));
    
        //这里的方法调用和插入图片是不同的。
        messageHelper.addAttachment("药水哥.gif",file);
    
        senderImpl.setUsername("[email protected]") ; // 根据自己的情况,设置username
        senderImpl.setPassword("授权码") ; // 根据自己的情况, 设置password
        Properties prop = new Properties() ;
        prop.put("mail.smtp.auth", "true") ; // 将这个参数设为true,让服务器进行认证,认证用户名和密码是否正确
        prop.put("mail.smtp.timeout", "25000") ;
        senderImpl.setJavaMailProperties(prop);
        //发送邮件
        senderImpl.send(mailMessage);

        System.out.println("邮件发送成功..");
    }
}

2.支持HTML样式的文本邮件

package com.thon.task;

import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.internet.MimeMessage;
import java.util.Properties;

/**

 * @description 文本邮件发送
 **/
public class HtmlMail {
    public static void main(String[] args) throws Exception{
        JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();

        //设定mail server
        senderImpl.setHost("smtp.qq.com");

        //建立邮件消息,发送简单邮件和html邮件的区别
        MimeMessage mailMessage = senderImpl.createMimeMessage();

        //注意这里的boolean,等于真的时候才能嵌套图片,在构建MimeMessageHelper时候,所给定的值是true表示启用,
        //multipart模式 为true时发送附件 可以设置html格式
        MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage);

        //设置收件人,寄件人
        messageHelper.setTo("[email protected]");
        messageHelper.setFrom("[email protected]");
        messageHelper.setSubject("测试邮件中上传附件112!!");  //邮件标题

        //true 表示启动HTML格式的邮件
        messageHelper.setText("

你好:附件中有学习资料!

",true); senderImpl.setUsername("[email protected]") ; // 根据自己的情况,设置username senderImpl.setPassword("授权码") ; // 根据自己的情况, 设置password Properties prop = new Properties() ; prop.put("mail.smtp.auth", "true") ; // 将这个参数设为true,让服务器进行认证,认证用户名和密码是否正确 prop.put("mail.smtp.timeout", "25000") ; senderImpl.setJavaMailProperties(prop); //发送邮件 senderImpl.send(mailMessage); System.out.println("邮件发送成功.."); } }

3.带图片的简单邮件

package com.thon.task;

import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.Properties;

/**
 * @description 内嵌图片邮件发送
 **/
public class ImageMail {
    public static void main(String[] args) throws Exception{
        JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();

        //设定mail server
        senderImpl.setHost("smtp.qq.com");

        //建立邮件消息,发送简单邮件和html邮件的区别
        MimeMessage mailMessage = senderImpl.createMimeMessage();

        //注意这里的boolean,等于真的时候才能嵌套图片,在构建MimeMessageHelper时候,所给定的值是true表示启用,
        //multipart模式 为true时发送附件 可以设置html格式
        MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage,true,"utf-8");

        //设置收件人,寄件人
        messageHelper.setTo("[email protected]");
        messageHelper.setFrom("[email protected]");
        messageHelper.setSubject("测试图片邮件!");

        //true 表示启动HTML格式的邮件
        messageHelper.setText("

hello!!spring image html mail

" + "",true); FileSystemResource file = new FileSystemResource(new File("/Users/thon/Pictures/漂亮/p2.jpg")); //插入图片 messageHelper.addInline("aaa",file); senderImpl.setUsername("[email protected]") ; // 根据自己的情况,设置username senderImpl.setPassword("授权码") ; // 根据自己的情况, 设置password Properties prop = new Properties() ; prop.put("mail.smtp.auth", "true") ; // 将这个参数设为true,让服务器进行认证,认证用户名和密码是否正确 prop.put("mail.smtp.timeout", "25000") ; senderImpl.setJavaMailProperties(prop); //发送邮件 senderImpl.send(mailMessage); System.out.println("邮件发送成功.."); } }

4.使用ssl加密发送带附件的html邮件:

package com.thon.schedule;

/**
 * Created by hucong on 2019-05-30.
 * 招标邮件
 */

import com.thon.commons.utils.StringUtils;
import com.thon.entity.system.Attachment;
import com.thon.model.BidMail;
import com.thon.model.BidPost;
import com.thon.model.BidPostSign;
import com.thon.service.system.AttachmentService;
import com.thon.service.utils.AttachmentUtil;
import com.thon.service.wzgl.BidMailService;
import com.thon.service.wzgl.BidPostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.internet.MimeMessage;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;


@Component
public class MailMessageSchedule {

    @Autowired
    private BidPostService bidPostService;
    @Autowired
    private BidMailService bidMailService;
    @Autowired
    private AttachmentService attachmentService;

    public void mailMessage()throws Exception {

        JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();
        System.setProperty("java.net.preferIPv4Stack", "true");
        //设定mail server
        senderImpl.setHost("smtp.qq.com");

        MimeMessage mailMessage = senderImpl.createMimeMessage();
        MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage,true,"utf-8");

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date currentTime = df.parse(df.format(new Date()));
        //获取已过截止日期招标记录
        List rbidPosts = bidPostService.selectByDate(currentTime);
        //获取已经发送过的招标信息
        List bidMails =bidMailService.selectByDate(currentTime);
        List bidPosts = new ArrayList<>(rbidPosts);
        for (BidPost p : rbidPosts){
            for (BidMail m : bidMails){
                if (m.getBidPostId().equals(p.getId())){
                    bidPosts.remove(p);
                }
            }
        }
        //发送邮件
        for (BidPost bidPost:bidPosts){
            String sendException ="success";
            String title = "询价招标通知函";
            String content = new String();
            String table = new String();
            for (BidPostSign s : bidPost.getOffers()){
                //供应商信息
                table += "" +
                        ""+s.getSupplierName()+"" +
                        ""+s.getSupplierCode()+"" +
                        ""+s.getLinkman()+"" +
                        ""+s.getPhone()+"" +
                        ""+(s.getSubmitDate()==null?"未填写日期":df.format(s.getSubmitDate()))+"" +
                        ""+(s.getApplyDate()==null?"未填写日期":df.format(s.getApplyDate()))+"" +
                        "" ;

                //供应商投标附件
                try
                {
                    if (!StringUtils.isNotBlank(s.getSubmitFiles())){
                        break;
                    }
                    Attachment attachment = attachmentService.getAttachment(Integer.valueOf(s.getSubmitFiles()));
                    if (attachment == null) {
                        attachment = new Attachment();
                    }
                    AttachmentUtil.read(attachment);
                    byte[] bytes = attachment.getBytes();
                    String fileName = URLEncoder.encode(attachment.getFileName(), "UTF-8");
                    String path = "/data/.material/tmp/"+"【投标文件】"+"【"+s.getSupplierName()+"】"+fileName;
                    // 根据绝对路径初始化文件
                    File localFile = new File(path);
                    //判断文件父目录是否存在
                    if (!localFile.getParentFile().exists()){
                        localFile.getParentFile().mkdir();
                    }
                    if (!localFile.exists())
                    {
                        localFile.createNewFile();
                    }
                    // 输出流
                    OutputStream os = new FileOutputStream(localFile);
                    os.write(bytes);
                    os.close();

                    messageHelper.addAttachment("【投标文件】"+"【"+s.getSupplierName()+"】"+fileName,localFile);
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                    bidMailService.save(bidPost,"file_read_error_submit:"+s.getId());
                }

                //供应商申请报价附件
                try
                {
                    if (!StringUtils.isNotBlank(s.getApplyFiles())){
                        break;
                    }
                    Attachment attachment = attachmentService.getAttachment(Integer.valueOf(s.getApplyFiles()));
                    if (attachment == null) {
                        attachment = new Attachment();
                    }
                    AttachmentUtil.read(attachment);
                    byte[] bytes = attachment.getBytes();
                    String fileName = URLEncoder.encode(attachment.getFileName(), "UTF-8");
                    String path = "/data/.material/tmp/"+"【申请报价】"+"【"+s.getSupplierName()+"】"+fileName;
                    // 根据绝对路径初始化文件
                    File localFile = new File(path);
                    if (!localFile.exists())
                    {
                        localFile.createNewFile();
                    }
                    // 输出流
                    OutputStream os = new FileOutputStream(localFile);
                    os.write(bytes);
                    os.close();

                    messageHelper.addAttachment("【申请报价】"+"【"+s.getSupplierName()+"】"+fileName,localFile);
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                    bidMailService.save(bidPost,"file_read_error_apply:"+s.getId());
                }

            }

            //设置收件人,寄件人
            if (bidPost.getEmails()!=null){
                //多邮箱用','分割
                String[] emails = bidPost.getEmails().split(",");
                messageHelper.setTo(emails);
            }
            else {
                bidMailService.save(bidPost,"email_error:"+bidPost.getEmails());
                return;
            }
            messageHelper.setFrom("[email protected]");
            messageHelper.setSubject(title);

            //true 表示启动HTML格式的邮件
            content="

采购信息发布标题:"+bidPost.getTitle()+"

" + "

采购分类:"+bidPost.getPriceType()+"

" + "

询价编号:"+bidPost.getCode()+"

" + "

申请单位:"+bidPost.getOfficeName()+"

" + "

发布者:"+bidPost.getAuthor()+"

" + "

发布日期:"+df.format(bidPost.getCreatedDate())+"

" + "

截止日期:"+df.format(bidPost.getDeadlineDate())+"

" + "


" + "

" + "

\n" + "" + "" + "" + "" + "" + "" + "" + "" + "" + table + "" + "
供应商名称组织机构联系人手机号报价时间申请报价时间
" + "
" + "附件:
" + "
" + "" + "

"; messageHelper.setText(content,true); senderImpl.setUsername("[email protected]") ; senderImpl.setPassword("授权码") ; //开启ssl Properties properties = new Properties(); properties.setProperty("mail.smtp.auth", "true");//开启认证 properties.setProperty("mail.debug", "true");//启用调试 properties.setProperty("mail.smtp.timeout", "200000");//设置链接超时 properties.setProperty("mail.smtp.port", Integer.toString(25));//设置端口 properties.setProperty("mail.smtp.socketFactory.port", Integer.toString(465));//设置ssl端口 properties.setProperty("mail.smtp.socketFactory.fallback", "false"); properties.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); senderImpl.setJavaMailProperties(properties); senderImpl.send(mailMessage); bidMailService.save(bidPost,sendException); System.out.println("邮件发送成功.."); System.out.println("定时器启动!"); } } }

 

你可能感兴趣的:(Java,工作内容)