email

作者: xueyueshuai | 来源:发表于2024-09-19 16:00 被阅读0次
package com.xys.java_test.controller.test.xys;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

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

@RestController
@RequestMapping("/api/test/xys/email")
public class EmailController {


    @PostMapping("/test1")
    public String test() {
        String res = sendEmail("1670226963@qq.com", "aaa", "bbbb");
        if (!"success".equals(res)) {
            return "发送失败:" + res;
        }
        return "发送成功";
    }


    public String sendEmail(String to, String subject, String body) {
        String smtpHost = "smtp.qq.com";
        String smtpPort = "465";
        String smtpAuth = "true";
        String socketFactoryClass = "javax.net.ssl.SSLSocketFactory";
        String socketFactoryFallback = "false";
        String socketFactoryPort = "465";
        String username = "1163798319@qq.com";
        String password = "***";

        Properties props = new Properties();
        props.put("mail.smtp.host", smtpHost);
        props.put("mail.smtp.port", smtpPort);
        props.put("mail.smtp.auth", smtpAuth);
        props.put("mail.smtp.socketFactory.class", socketFactoryClass);
        props.put("mail.smtp.socketFactory.fallback", socketFactoryFallback);
        props.put("mail.smtp.socketFactory.port", socketFactoryPort);

        Session session = Session.getInstance(props, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });

        try {
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(username));
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            message.setSubject(subject);
            message.setText(body);
            Transport.send(message);
            return "success";
        } catch (MessagingException e) {
            return e.getMessage();
            // throw new RuntimeException(e);
        }
    }

}

相关文章

网友评论

      本文标题:email

      本文链接:https://www.haomeiwen.com/subject/htnoljtx.html