• 发送邮件(代码库)


    pom.xml

    <dependency>
        <groupId>com.sun.mail</groupId>
        <artifactId>javax.mail</artifactId>
        <version>1.5.6</version>
    </dependency>

    MailSenderInfo.java

    import com.sun.mail.util.MailSSLSocketFactory;
    
    import java.security.GeneralSecurityException;
    import java.util.Properties;
    
    public class MailSenderInfo {
    
        // 发送邮件的服务器的IP和端口
        private String mailServerHost;
        private String mailServerPort = "25";
        // 邮件发送者的地址
        private String fromAddress;
        // 邮件接收者的地址
        private String toAddress;
    
        private String password;
        // 是否需要身份验证
        private boolean validate = false;
        // 邮件主题
        private String subject;
        // 邮件的文本内容
        private String content;
        // 邮件附件的文件名
        private String[] attachFileNames;
        //邮件发件人昵称
        private String nick;
    
        private boolean ssl;
    
        public String getNick() {
            return nick;
        }
    
        public boolean isSsl() {
            return ssl;
        }
    
        public void setSsl(boolean ssl) {
            this.ssl = ssl;
        }
    
        public void setNick(String nick) {
            this.nick = nick;
        }
    
        private String httpServer;
        private MailType type = MailType.TEXT;//html or text;
    
        enum MailType {
            TEXT, HTML;
        }
    
        /** */
        /**
         * 获得邮件会话属性
         */
        public Properties getProperties() {
            Properties p = new Properties();
            p.put("mail.smtp.host", this.mailServerHost);
            p.put("mail.smtp.port", this.mailServerPort);
            p.put("mail.smtp.auth", validate ? "true" : "false");
            if (ssl) {
                try {
                    MailSSLSocketFactory sf = new MailSSLSocketFactory();
                    sf.setTrustAllHosts(true);
                    p.put("mail.smtp.ssl.enable", "true");
                    p.put("mail.smtp.ssl.socketFactory", sf);
                } catch (GeneralSecurityException e) {
                }
    
            }
            return p;
        }
    
        public String getMailServerHost() {
            return mailServerHost;
        }
    
        public void setMailServerHost(String mailServerHost) {
            this.mailServerHost = mailServerHost;
        }
    
        public String getMailServerPort() {
            return mailServerPort;
        }
    
        public void setMailServerPort(String mailServerPort) {
            this.mailServerPort = mailServerPort;
        }
    
        public boolean isValidate() {
            return validate;
        }
    
        public void setValidate(boolean validate) {
            this.validate = validate;
        }
    
        public String[] getAttachFileNames() {
            return attachFileNames;
        }
    
        public void setAttachFileNames(String[] fileNames) {
            this.attachFileNames = fileNames;
        }
    
        public String getFromAddress() {
            return fromAddress;
        }
    
        public void setFromAddress(String fromAddress) {
            this.fromAddress = fromAddress;
        }
    
        public String getPassword() {
            return password;
        }
    
        public void setPassword(String password) {
            this.password = password;
        }
    
        public String getToAddress() {
            return toAddress;
        }
    
        public void setToAddress(String toAddress) {
            this.toAddress = toAddress;
        }
    
    
        public String getSubject() {
            return subject;
        }
    
        public void setSubject(String subject) {
            this.subject = subject;
        }
    
        public String getContent() {
            return content;
        }
    
        public void setContent(String textContent) {
            this.content = textContent;
        }
    
        public String getHttpServer() {
            return httpServer;
        }
    
        public void setHttpServer(String httpServer) {
            this.httpServer = httpServer;
        }
    
        public MailType getType() {
            return type;
        }
    
        public void setType(MailType type) {
            this.type = type;
        }
    
        @Override
        public String toString() {
            return "MailSenderInfo [mailServerHost=" + mailServerHost + ", mailServerPort=" + mailServerPort
                    + ", fromAddress=" + fromAddress + ", toAddress=" + toAddress + ", content=" + content + ", httpServer="
                    + httpServer + ", type=" + type + "]";
        }
    
    
    }
    View Code

    MyAuthenticator.java

    import javax.mail.Authenticator;
    import javax.mail.PasswordAuthentication;
    
    public class MyAuthenticator extends Authenticator {
    
        String userName = null;
        String password = null;
    
        public MyAuthenticator() {
        }
    
        public MyAuthenticator(String username, String password) {
            this.userName = username;
            this.password = password;
        }
    
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(userName, password);
        }
        
    }
    View Code

    Test.java

    import javax.activation.DataHandler;
    import javax.activation.FileDataSource;
    import javax.mail.*;
    import javax.mail.internet.*;
    import java.util.Date;
    import java.util.Properties;
    
    /**
     * @author jiash
     * @since 2021/10/8
     */
    public class Test {
        private static final String CHARSET = "UTF-8";
    
        public static boolean sendTextMail(MailSenderInfo mailInfo) {
            MyAuthenticator authenticator = null;
            Properties pro = mailInfo.getProperties();
            if (mailInfo.isValidate()) {
                // 如果需要身份认证,则创建一个密码验证器
                authenticator = new MyAuthenticator(mailInfo.getFromAddress(),
                        mailInfo.getPassword());
            }
            Session sendMailSession = Session.getInstance(pro, authenticator);
            try {
                // 根据session创建一个邮件通知
                MimeMessage mailMessage = new MimeMessage(sendMailSession);
                // 创建邮件发送者地址
                Address from = new InternetAddress(mailInfo.getFromAddress());
                if (mailInfo.getNick() != null && !"".equals(mailInfo.getNick())) {
                    String nickName;
                    try {
                        nickName = javax.mail.internet.MimeUtility.encodeText(mailInfo.getNick());
                        mailMessage.setFrom(new InternetAddress(nickName + " <" + from + ">"));
                    } catch (Exception e) {
                    }
                } else {
                    // 设置邮件通知的发送者
                    mailMessage.setFrom(from);
                }
    
    
                // 创建邮件的接收者地址,并设置到邮件通知中
                Address to = new InternetAddress(mailInfo.getToAddress());
                mailMessage.setRecipient(Message.RecipientType.TO, to);
                // 设置邮件通知的主题
                mailMessage.setSubject(mailInfo.getSubject(), CHARSET);
                // 设置邮件通知发送的时间
                mailMessage.setSentDate(new Date());
    
                Multipart mp = new MimeMultipart();
                MimeBodyPart mbpContent = new MimeBodyPart();
                mbpContent.setContent(mailInfo.getContent(),
                        "text/plain;charset=utf-8");
                mp.addBodyPart(mbpContent);
    
                if (mailInfo.getAttachFileNames() != null) {
    
                    for (String fileName : mailInfo.getAttachFileNames()) {
                        MimeBodyPart mbpFile = new MimeBodyPart();
                        FileDataSource fds = new FileDataSource(fileName);
                        mbpFile.setDataHandler(new DataHandler(fds));
                        // 解决预发环境的发送邮件时附件的标题乱码问题
                        mbpFile.setFileName(MimeUtility.encodeText(fds.getName()));
                        mp.addBodyPart(mbpFile);
                    }
                }
    
                // 设置邮件通知的主要内容
                mailMessage.setContent(mp);
                // 发送邮件
                Transport.send(mailMessage);
                return true;
            } catch (Exception ex) {
            }
            return false;
        }
    
    
        /**
         * 以HTML格式发送邮件
         *
         * @param mailInfo 待发送的邮件信息
         */
        public static boolean sendHtmlMail(MailSenderInfo mailInfo) {
            // 判断是否需要身份认证
            MyAuthenticator authenticator = null;
            Properties pro = mailInfo.getProperties();
            // 如果需要身份认证,则创建一个密码验证器
            if (mailInfo.isValidate()) {
                authenticator = new MyAuthenticator(mailInfo.getFromAddress(),
                        mailInfo.getPassword());
            }
            // 根据邮件会话属性和密码验证器构造一个发送邮件的session
            Session sendMailSession = Session.getInstance(pro, authenticator);
            try {
                // 根据session创建一个邮件通知
                MimeMessage mailMessage = new MimeMessage(sendMailSession);
                // 创建邮件发送者地址
                Address from = new InternetAddress(mailInfo.getFromAddress());
                // 设置邮件通知的发送者
                mailMessage.setFrom(from);
                // 创建邮件的接收者地址,并设置到邮件通知中
                Address to = new InternetAddress(mailInfo.getToAddress());
                // Message.RecipientType.TO属性表示接收者的类型为TO
                mailMessage.setRecipient(Message.RecipientType.TO, to);
                // 设置邮件通知的主题
                mailMessage.setSubject(mailInfo.getSubject(), CHARSET);
                // 设置邮件通知发送的时间
                mailMessage.setSentDate(new Date());
                // MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象
                Multipart mainPart = new MimeMultipart();
    
                if (mailInfo.getAttachFileNames() != null) {
                    /*MimeBodyPart mbpContent = new MimeBodyPart();
                    mbpContent.setContent(mailInfo.getContent(),
                            "text/plain;charset=utf-8");
                    mainPart.addBodyPart(mbpContent);*/
                    for (String fileName : mailInfo.getAttachFileNames()) {
                        MimeBodyPart mbpFile = new MimeBodyPart();
                        FileDataSource fds = new FileDataSource(fileName);
                        mbpFile.setDataHandler(new DataHandler(fds));
                        // 解决预发环境的发送邮件时附件的标题乱码问题
                        mbpFile.setFileName(MimeUtility.encodeText(fds.getName()));
                        mainPart.addBodyPart(mbpFile);
                    }
                }
    
                // 创建一个包含HTML内容的MimeBodyPart
                BodyPart html = new MimeBodyPart();
                // 设置HTML内容
                html.setContent(mailInfo.getContent(), "text/html; charset=utf-8");
                mainPart.addBodyPart(html);
                // 创建一个包含图表的的MimeBodyPart
                // 将MiniMultipart对象设置为邮件内容
                mailMessage.setContent(mainPart);
                // 发送邮件
                Transport.send(mailMessage);
                return true;
            } catch (Exception ex) {
            }
            return false;
        }
    
    
        public static void main(String[] args) {
            MailSenderInfo mailInfo = new MailSenderInfo();
    
            mailInfo.setMailServerHost("smtp.sina.net");
            mailInfo.setPassword("解密后的明文密码xxxxx");
            mailInfo.setFromAddress("user@mail.xxxx.com");
            mailInfo.setMailServerPort("25");
            mailInfo.setValidate(true);
    
            mailInfo.setToAddress("1214369231@qq.com");
            mailInfo.setSubject("测试主题");
            mailInfo.setContent("测试一下");
            sendTextMail(mailInfo);
        }
    }
    View Code

    原创文章,欢迎转载,转载庆注明出处!

    把每一件简单的事情做好,就是不简单;把每一件平凡的事情做好,就是不平凡!相信自己,创造奇迹~~
  • 相关阅读:
    poj 2362 Square
    poj 1011 Sticks
    hust 1062 Divisibility
    hdu 4115 Eliminate the Conflict
    Android
    android stdio 快捷键
    Android Lint的使用
    Android studio导出配置
    fragment显示 Binary XML file line #12: Error inflating class fragment 错误
    markdown 字体颜色
  • 原文地址:https://www.cnblogs.com/acm-bingzi/p/mail.html
Copyright © 2020-2023  润新知