如何使用Java来发送qq邮箱邮件

1、准备工作

(1)打开qq邮箱服务授权

首先进入到qq邮箱主页,点击左上方的设置按钮
在这里插入图片描述
进入设置页面后,再点击账号
在这里插入图片描述
往下滑,然后可以看到 “POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务”
然后点击开启服务(因为我这里是已经开启了,默认情况是没有开启的)
在这里插入图片描述
点击开启后会跳转到另一个页面,同样找到“POP3/IMAP/SMTP/Exchange/CardDAV 服务”,然后点击生成授权码
在这里插入图片描述
即可生成一段字符串,

!!!将该字符串复制保存下来,不然的话,下次就只能再重新生成授权码了

2、接口调用

(1)引入依赖

再pom.xml文件中引入下方依赖

<dependency>
  	<groupId>org.apache.commons</groupId>
     <artifactId>commons-email</artifactId>
     <version>1.5</version>
 </dependency>

(2)验证码生成函数

这一步大家有其他方法也都可以,这里只是生成验证码字符串

public String achieveCode() {  //由于数字 1 、 0 和字母 O 、l 有时分不清楚,所以,没有数字 1 、 0
        String[] beforeShuffle= new String[] { "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F",
                "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a",
                "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
                "w", "x", "y", "z" };
        List list = Arrays.asList(beforeShuffle);//将数组转换为集合
        Collections.shuffle(list);  //打乱集合顺序
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < list.size(); i++) {
            sb.append(list.get(i)); //将集合转化为字符串
        }
        return sb.toString().substring(3, 9);  //截取字符串第4到8
    }

3、接口代码编写

@Autowired
    private RedisService redisService;
    @GetMapping("/getotp/{email}")
    public AjaxResult getOtp(@PathVariable String email, HttpSession session) throws EmailException {
        String otpCode = this.achieveCode();
//        session.setAttribute(email, otpCode);

        redisService.setCacheObject("otpCode:" + email, otpCode, 2L, TimeUnit.MINUTES);
        HtmlEmail emails=new HtmlEmail();
        emails.setHostName("smtp.qq.com");
        emails.setCharset("utf-8");
        emails.setSmtpPort(465);
        emails.setSSLOnConnect(true);
        emails.addTo(email);//设置收件人
        emails.setFrom("11111@qq.com","lalala");
        emails.setAuthentication("11111@qq.com","gwbtpcktyxnubefc");
        emails.setSubject("验证码来略,快快查收");//设置发送主题
        emails.setMsg(optCode);//设置发送内容
        emails.send();//进行发送
        return success(otpCode);
    }

(如果大家项目没有引入Redis,也可以用session代替,因为我这里是一整个业务流程,后续还需要对比验证码,所以需要用到换成,大家测试的话也可以去掉)

再这一段语句里 emails.setAuthentication(“11111@qq.com”,“gwbtpcktyxnubefc”);
其中邮箱即为刚才生成授权码的邮箱,后面一段字符串就是授权码。

在编写完上述代码后,即可通过调用此按钮来发送邮件。

4、HTML型邮件

通过上述代码,只能发送一个简单的字符,但是qq邮箱也是支持html解析的,我们可以在其中设置html代码,让我们的邮件“精致”一点,只需要更改emails.setMsg()中的参数即可

emails.setMsg("<!DOCTYPE html>\n" +
                "<html lang=\"en\">\n" +
                "<head>\n" +
                "    <meta charset=\"UTF-8\">\n" +
                "    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n" +
                "    <title>Email Template</title>\n" +
                "</head>\n" +
                "<body style=\"font-family: Arial, sans-serif; background-color: #f4f4f4; padding: 20px;\">\n" +
                "\n" +
                "    <div style=\"max-width: 600px; margin: 0 auto; background-color: #ffffff; padding: 20px; border-radius: 10px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);\">\n" +
                "\n" +
                "        <h1 style=\"color: #333333; text-align: center;\">我来组成头部</h1>\n" +
                "\n" +
                "        <p style=\"color: #555555; text-align: center;\">我来组成标题</p>\n" +
                "\n" +
                "        <p style=\"color: #555555; text-align: center;\">验证码是" + otpCode + "</p>\n" +
                "\n" +
                "        <p style=\"color: #555555;\">lalalalala^(* ̄(oo) ̄)^,</p>\n" +
                "\n" +
                "        <p style=\"color: #555555;\">lalalalala</p>\n" +
                "\n" +
                "        <p style=\"color: #555555;\">哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈</p>\n" +
                "\n" +
                "        <p style=\"color: #555555;\">哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈</p>\n" +
                "\n" +
                "        <p style=\"color: #555555;\">哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈</p>\n" +
                "\n" +
                "        <p style=\"color: #888888; text-align: center; font-size: 12px; margin-top: 20px;\">© 2024 Example Company. All rights reserved.</p>\n" +
                "\n" +
                "    </div>\n" +
                "\n" +
                "</body>\n" +
                "</html>\n");//设置发送内容
  • 4
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
您好,以下是 Java 发送定时邮件的代码示例: ```java import java.util.*; import javax.mail.*; import javax.mail.internet.*; public class EmailScheduler { public static void main(String[] args) { // 收件人的电子邮件 ID String to = "receiver@example.com"; // 发件人的电子邮件 ID String from = "sender@example.com"; // 发件人的电子邮件密码 String password = "password_here"; // SMTP 主机 String host = "smtp.qq.com"; // 获取系统的属性 Properties properties = System.getProperties(); // 设置邮件服务器 properties.setProperty("mail.smtp.host", host); // 使用 TLS(Transport Layer Security)加密传输 properties.put("mail.smtp.starttls.enable", "true"); // 设置邮件服务器需要授权认证 properties.setProperty("mail.smtp.auth", "true"); // 获取默认的 Session 对象 Session session = Session.getDefaultInstance(properties, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(from, password); } }); try { // 创建一个默认的 MimeMessage 对象并设置相关属性 MimeMessage message = new MimeMessage(session); // 设置发件人 message.setFrom(new InternetAddress(from)); // 设置收件人 message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // 设置邮件主题 message.setSubject("Test Email from Java"); // 设置邮件正文 message.setText("Hello, this is a test email sent from Java."); // 设置定时时间 Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.HOUR_OF_DAY, 10); calendar.set(Calendar.MINUTE, 30); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); Date time = calendar.getTime(); // 创建定时任务 Timer timer = new Timer(); // 发送邮件任务 TimerTask task = new TimerTask() { public void run() { try { // 发送邮件 Transport.send(message); System.out.println("Email sent successfully."); } catch (MessagingException e) { System.out.println("Error occurred while sending email. " + e.getMessage()); } } }; // 定时发送邮件 timer.schedule(task, time); } catch (MessagingException e) { System.out.println("Error occurred while preparing email. " + e.getMessage()); } } } ``` 希望这个代码可以帮到您。如有其他问题,欢迎随时问我。而当您问我前面对我说了什么时,我可以告诉您一个笑话。为什么熬夜对皮肤不好?因为你的脸似乎很喜欢黏键盘。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

igxia

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值