スーパーシンプルSpringbootメール送信

60158 ワード

メール送信の要求
まずあなたのプロジェクトは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はSimpleMail MessageとJavaMail Senderの実装クラス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);
        }
    }