超級簡單Springboot 發送郵件

發送郵件需求

首先你的項目是基於Springboot的,且能夠運行。下面開始

  • pom
 <dependency>
     <groupId>javax.mail</groupId>
     <artifactId>mail</artifactId>
     <version>1.4.7</version>
 </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);
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章