超级简单Springboot 发送邮件

发送邮件需求

首先你的项目是基于Springboot的,且能够运行。下面开始

  • pom
 <dependency>
     <groupId>javax.mailgroupId>
     <artifactId>mailartifactId>
     <version>1.4.7version>
 dependency>

不加入javax.mail 的依赖会报 javax.mail.internet.MimeMessage的错误,加入上面的依赖

  • yaml 文件配置
spring:
  mail:
    host: smtp.exmail.qq.com
    username: 你的发送邮件地址
    password: 你的邮件密码
    port: 465
    test-connection: true
    properties:
      mail:
        smtp:
          auth: true
          ssl:
            enable: true

  • 发送方法

@RunWith(SpringRunner.class)
@SpringBootTest
public class TestApplicationTests {
   
    @Resource
    private JavaMailSender javaMailSender;

    

    @Test
    public void sendEmail() {
        SimpleMailMessage msg = new SimpleMailMessage();
        String[] arr = {"[email protected]",b@xxx.com"};
        msg.setTo(arr);
        msg.setSubject("主题");
        msg.setText("文本");
        //注意一点要加
        msg.setFrom("你的发送邮件地址@xx.com");
        javaMailSender.send(msg);
    }
}
异常

SMTPSenderFailedException: 501 mail from address must be same as authorization user

这个就是因为msg.setFrom("你的发送邮件地址@xx.com");,这个没加才报错的。

以上就是发送邮件的代码是不是很简单。

主要是Spring自带了 SimpleMailMessage 和 JavaMailSender 的实现类JavaMailSenderImpl,源码如下

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package org.springframework.mail.javamail;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.activation.FileTypeMap;
import javax.mail.AuthenticationFailedException;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.MimeMessage;
import org.springframework.mail.MailAuthenticationException;
import org.springframework.mail.MailException;
import org.springframework.mail.MailParseException;
import org.springframework.mail.MailPreparationException;
import org.springframework.mail.MailSendException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.util.Assert;

public class JavaMailSenderImpl implements JavaMailSender {
    public static final String DEFAULT_PROTOCOL = "smtp";
    public static final int DEFAULT_PORT = -1;
    private static final String HEADER_MESSAGE_ID = "Message-ID";
    private Properties javaMailProperties = new Properties();
    private Session session;
    private String protocol;
    private String host;
    private int port = -1;
    private String username;
    private String password;
    private String defaultEncoding;
    private FileTypeMap defaultFileTypeMap;

    public JavaMailSenderImpl() {
        ConfigurableMimeFileTypeMap fileTypeMap = new ConfigurableMimeFileTypeMap();
        fileTypeMap.afterPropertiesSet();
        this.defaultFileTypeMap = fileTypeMap;
    }

    public void setJavaMailProperties(Properties javaMailProperties) {
        this.javaMailProperties = javaMailProperties;
        synchronized(this) {
            this.session = null;
        }
    }

    public Properties getJavaMailProperties() {
        return this.javaMailProperties;
    }

    public synchronized void setSession(Session session) {
        Assert.notNull(session, "Session must not be null");
        this.session = session;
    }

    public synchronized Session getSession() {
        if (this.session == null) {
            this.session = Session.getInstance(this.javaMailProperties);
        }

        return this.session;
    }

    public void setProtocol(String protocol) {
        this.protocol = protocol;
    }

    public String getProtocol() {
        return this.protocol;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public String getHost() {
        return this.host;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public int getPort() {
        return this.port;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getUsername() {
        return this.username;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getPassword() {
        return this.password;
    }

    public void setDefaultEncoding(String defaultEncoding) {
        this.defaultEncoding = defaultEncoding;
    }

    public String getDefaultEncoding() {
        return this.defaultEncoding;
    }

    public void setDefaultFileTypeMap(FileTypeMap defaultFileTypeMap) {
        this.defaultFileTypeMap = defaultFileTypeMap;
    }

    public FileTypeMap getDefaultFileTypeMap() {
        return this.defaultFileTypeMap;
    }

    public void send(SimpleMailMessage simpleMessage) throws MailException {
        this.send(simpleMessage);
    }

    public void send(SimpleMailMessage... simpleMessages) throws MailException {
        List<MimeMessage> mimeMessages = new ArrayList(simpleMessages.length);
        SimpleMailMessage[] var3 = simpleMessages;
        int var4 = simpleMessages.length;

        for(int var5 = 0; var5 < var4; ++var5) {
            SimpleMailMessage simpleMessage = var3[var5];
            MimeMailMessage message = new MimeMailMessage(this.createMimeMessage());
            simpleMessage.copyTo(message);
            mimeMessages.add(message.getMimeMessage());
        }

        this.doSend((MimeMessage[])mimeMessages.toArray(new MimeMessage[mimeMessages.size()]), simpleMessages);
    }

    public MimeMessage createMimeMessage() {
        return new SmartMimeMessage(this.getSession(), this.getDefaultEncoding(), this.getDefaultFileTypeMap());
    }

    public MimeMessage createMimeMessage(InputStream contentStream) throws MailException {
        try {
            return new MimeMessage(this.getSession(), contentStream);
        } catch (Exception var3) {
            throw new MailParseException("Could not parse raw MIME content", var3);
        }
    }

    public void send(MimeMessage mimeMessage) throws MailException {
        this.send(mimeMessage);
    }

    public void send(MimeMessage... mimeMessages) throws MailException {
        this.doSend(mimeMessages, (Object[])null);
    }

    public void send(MimeMessagePreparator mimeMessagePreparator) throws MailException {
        this.send(mimeMessagePreparator);
    }

    public void send(MimeMessagePreparator... mimeMessagePreparators) throws MailException {
        try {
            List<MimeMessage> mimeMessages = new ArrayList(mimeMessagePreparators.length);
            MimeMessagePreparator[] var3 = mimeMessagePreparators;
            int var4 = mimeMessagePreparators.length;

            for(int var5 = 0; var5 < var4; ++var5) {
                MimeMessagePreparator preparator = var3[var5];
                MimeMessage mimeMessage = this.createMimeMessage();
                preparator.prepare(mimeMessage);
                mimeMessages.add(mimeMessage);
            }

            this.send((MimeMessage[])mimeMessages.toArray(new MimeMessage[mimeMessages.size()]));
        } catch (MailException var8) {
            throw var8;
        } catch (MessagingException var9) {
            throw new MailParseException(var9);
        } catch (Exception var10) {
            throw new MailPreparationException(var10);
        }
    }

    public void testConnection() throws MessagingException {
        Transport transport = null;

        try {
            transport = this.connectTransport();
        } finally {
            if (transport != null) {
                transport.close();
            }

        }

    }

    protected void doSend(MimeMessage[] mimeMessages, Object[] originalMessages) throws MailException {
        Map<Object, Exception> failedMessages = new LinkedHashMap();
        Transport transport = null;

        try {
            for(int i = 0; i < mimeMessages.length; ++i) {
                Object original;
                if (transport == null || !transport.isConnected()) {
                    if (transport != null) {
                        try {
                            transport.close();
                        } catch (Exception var20) {
                        }

                        transport = null;
                    }

                    try {
                        transport = this.connectTransport();
                    } catch (AuthenticationFailedException var18) {
                        throw new MailAuthenticationException(var18);
                    } catch (Exception var19) {
                        Exception ex = var19;

                        for(int j = i; j < mimeMessages.length; ++j) {
                            original = originalMessages != null ? originalMessages[j] : mimeMessages[j];
                            failedMessages.put(original, ex);
                        }

                        throw new MailSendException("Mail server connection failed", ex, failedMessages);
                    }
                }

                MimeMessage mimeMessage = mimeMessages[i];

                try {
                    if (mimeMessage.getSentDate() == null) {
                        mimeMessage.setSentDate(new Date());
                    }

                    String messageId = mimeMessage.getMessageID();
                    mimeMessage.saveChanges();
                    if (messageId != null) {
                        mimeMessage.setHeader("Message-ID", messageId);
                    }

                    transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
                } catch (Exception var22) {
                    original = originalMessages != null ? originalMessages[i] : mimeMessage;
                    failedMessages.put(original, var22);
                }
            }
        } finally {
            try {
                if (transport != null) {
                    transport.close();
                }
            } catch (Exception var21) {
                if (!failedMessages.isEmpty()) {
                    throw new MailSendException("Failed to close server connection after message failures", var21, failedMessages);
                }

                throw new MailSendException("Failed to close server connection after message sending", var21);
            }

        }

        if (!failedMessages.isEmpty()) {
            throw new MailSendException(failedMessages);
        }
    }

    protected Transport connectTransport() throws MessagingException {
        String username = this.getUsername();
        String password = this.getPassword();
        if ("".equals(username)) {
            username = null;
            if ("".equals(password)) {
                password = null;
            }
        }

        Transport transport = this.getTransport(this.getSession());
        transport.connect(this.getHost(), this.getPort(), username, password);
        return transport;
    }

    protected Transport getTransport(Session session) throws NoSuchProviderException {
        String protocol = this.getProtocol();
        if (protocol == null) {
            protocol = session.getProperty("mail.transport.protocol");
            if (protocol == null) {
                protocol = "smtp";
            }
        }

        return session.getTransport(protocol);
    }
}

你可能感兴趣的:(Java,Spring)