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

常见错误:

1.关于使用Java Mail进行邮件发送,抛出Could not connect to SMTP host: xx@xxx.com, 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(1837287700@qq.com);
        //发件人
        messageHelper.setFrom("1837287700@qq.com");
        //设置邮件标题
        messageHelper.setSubject(“标题”);
        //设置邮件内容,true表示开启HTML文本格式  
        messageHelper.setText(content,true);
        //这是发件人邮箱信息,username表示用户邮箱,password表示对应邮件授权码
        senderImpl.setUsername("1837287700@qq.com") ;
        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(1837287700@qq.com);
        //发件人
        messageHelper.setFrom("1837287700@qq.com");
        //设置邮件标题
        messageHelper.setSubject(“标题”);
        //设置邮件内容,true表示开启HTML文本格式  
        messageHelper.setText(content,true);
        //这是发件人邮箱信息,username表示用户邮箱,password表示对应邮件授权码
        senderImpl.setUsername("1837287700@qq.com") ;
        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("hu.cong@outlook.com");
        messageHelper.setFrom("1837287700@qq.com");
        messageHelper.setSubject("测试邮件中上传附件!");

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

        FileSystemResource file = new FileSystemResource(new File("E:\\新建文件夹 (2)\\ysg.gif"));
    
        //这里的方法调用和插入图片是不同的。
        messageHelper.addAttachment("药水哥.gif",file);
    
        senderImpl.setUsername("1837287700@qq.com") ; // 根据自己的情况,设置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("hu.cong@outlook.com");
        messageHelper.setFrom("1837287700@qq.com");
        messageHelper.setSubject("测试邮件中上传附件112!!");  //邮件标题

        //true 表示启动HTML格式的邮件
        messageHelper.setText("<html><head></head><body><h1>你好:附件中有学习资料!</h1></body></html>",true);

        senderImpl.setUsername("1837287700@qq.com") ; // 根据自己的情况,设置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("1837287700@qq.com");
        messageHelper.setFrom("1837287700@qq.com");
        messageHelper.setSubject("测试图片邮件!");

        //true 表示启动HTML格式的邮件
        messageHelper.setText("<html><head></head><body><h1>hello!!spring image html mail</h1>" +
                "<img src=\"cid:aaa\"/></body></html>",true);

        FileSystemResource file = new FileSystemResource(new File("/Users/thon/Pictures/漂亮/p2.jpg"));

        //插入图片
        messageHelper.addInline("aaa",file);

        senderImpl.setUsername("1837287700@qq.com") ; // 根据自己的情况,设置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<BidPost> rbidPosts = bidPostService.selectByDate(currentTime);
        //获取已经发送过的招标信息
        List<BidMail> bidMails =bidMailService.selectByDate(currentTime);
        List<BidPost> 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 += "<tr>" +
                        "<td>"+s.getSupplierName()+"</td>" +
                        "<td>"+s.getSupplierCode()+"</td>" +
                        "<td>"+s.getLinkman()+"</td>" +
                        "<td>"+s.getPhone()+"</td>" +
                        "<td>"+(s.getSubmitDate()==null?"未填写日期":df.format(s.getSubmitDate()))+"</td>" +
                        "<td>"+(s.getApplyDate()==null?"未填写日期":df.format(s.getApplyDate()))+"</td>" +
                        "</tr>" ;

                //供应商投标附件
                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("1837287700@qq.com");
            messageHelper.setSubject(title);

            //true 表示启动HTML格式的邮件
            content="<p>采购信息发布标题:"+bidPost.getTitle()+" </p>" +
                    "<p>采购分类:"+bidPost.getPriceType()+"</p>" +
                    "<p>询价编号:"+bidPost.getCode()+"</p>" +
                    "<p>申请单位:"+bidPost.getOfficeName()+"</p>" +
                    "<p>发布者:"+bidPost.getAuthor()+"</p>" +
                    "<p>发布日期:"+df.format(bidPost.getCreatedDate())+"</p>" +
                    "<p>截止日期:"+df.format(bidPost.getDeadlineDate())+"</p>" +
                    "<p><br /></p>" +
                    "<p><span id=\"__kindeditor_bookmark_start_10__\">" +
                    "<table style=\"width:100%;\" cellpadding=\"2\" cellspacing=\"0\" border=\"1\" bordercolor=\"#000000\">\n" +
                    "<tbody>" +
                    "<tr>" +
                    "<td>供应商名称</td>" +
                    "<td>组织机构</td>" +
                    "<td>联系人</td>" +
                    "<td>手机号</td>" +
                    "<td>报价时间</td>" +
                    "<td>申请报价时间</td>" +
                    "</tr>" +
                    table +
                    "</tbody>" +
                    "</table>" +
                    "<br />" +
                    "<span id=\"__kindeditor_bookmark_start_90__\"></span>附件:<br />" +
                    "<br />" +
                    "</span>" +
                    "</p>";
            messageHelper.setText(content,true);
            senderImpl.setUsername("1837287700@qq.com") ;
            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("定时器启动!");

        }

    }



}

  • 6
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
使用Java发送QQ邮件,你需要遵循以下步骤: 1. 导入JavaMailJava Activation Framework (JAF)的相关库。 2. 设置QQ邮箱的SMTP服务器及端口号。QQ邮箱的SMTP服务器是smtp.qq.com,端口号是465或587。 3. 创建一个Properties对象,并设置SMTP服务器相关属性。其中包括邮件服务器地址(mail.smtp.host),端口号(mail.smtp.port),使用的加密类型(mail.smtp.ssl.enable),是否需要身份验证(mail.smtp.auth)等。 4. 创建Session对象,用于与SMTP服务器进行通信。使用Properties对象作为参数来实例化Session对象。 5. 创建一个MimeMessage实例,该实例将包含要发送的电子邮件的内容。 6. 设置发件人地址、收件人地址、邮件主题和正文等属性。 7. 创建一个Transport对象,并使用Session对象和发件人的邮箱账号及密码进行身份验证。 8. 发送邮件使用Transport对象的静态方法send()来发送MimeMessage实例。 以下是一个使用Java代码发送QQ邮件的示例: ```java import java.util.Properties; import javax.mail.*; import javax.mail.internet.*; public class QQEmailSender { public static void main(String[] args) throws MessagingException { String from = "你的QQ邮箱地址"; String password = "你的QQ邮箱授权码"; String to = "收件人邮箱地址"; Properties properties = new Properties(); properties.put("mail.smtp.host", "smtp.qq.com"); properties.put("mail.smtp.port", "587"); properties.put("mail.smtp.ssl.enable", "true"); properties.put("mail.smtp.auth", "true"); Session session = Session.getInstance(properties, new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(from, password); } }); Message message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.setRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject("Java发送QQ邮件"); message.setText("这是使用Java发送的一封QQ邮件。"); Transport.send(message); System.out.println("邮件发送成功!"); } } ``` 请确保替换代码中的"你的QQ邮箱地址"、"你的QQ邮箱授权码"和"收件人邮箱地址"为正确的邮箱地址和授权码,并保证你的QQ邮箱已开启SMTP服务。 这是一个基本的示例,你可以根据自己的需求进行修改和扩展。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值