zoukankan      html  css  js  c++  java
  • Java 邮件发送

    实现邮件发送功能:EmailUtil.java

    //导入包名
    import java.util.ArrayList;  
    import java.util.Collection;  
    import java.util.Date;  
    import java.util.Iterator;  
    import java.util.List;  
    import java.util.Properties;  
    import javax.activation.DataHandler;  
    import javax.activation.FileDataSource;  
    import javax.mail.Authenticator;  
    import javax.mail.Message;  
    import javax.mail.Multipart;  
    import javax.mail.PasswordAuthentication;  
    import javax.mail.SendFailedException;  
    import javax.mail.Session;  
    import javax.mail.Transport;  
    import javax.mail.internet.InternetAddress;  
    import javax.mail.internet.MimeBodyPart;  
    import javax.mail.internet.MimeMessage;  
    import javax.mail.internet.MimeMultipart;  
      
    import org.apache.commons.logging.Log;  
    import org.apache.commons.logging.LogFactory;  
      
    public class EmailUtil {  
        private final static String default_charset = "UTF-8";  
      
        public static enum EncryptionTypes {  
            Default, TLS, SSL  
        }  
      
        static final Log logger = LogFactory.getLog(EmailUtil.class);  
        private String mail_host = "";  
        private int mail_port = 25;  
        private int encryptionType = EncryptionTypes.Default.ordinal();  
        private boolean auth = false;  
        private String mail_host_account = "";  
        private String mail_host_password = "";  
        private boolean isHtml = true;  
      
        public EmailUtil(String mail_host) {  
            this.mail_host = mail_host;  
        }  
      
        public EmailUtil(String mail_host, boolean auth, String account, String password) {  
            this(mail_host, 25, EncryptionTypes.Default.ordinal(), auth, account, password);  
        }  
      
        public EmailUtil(String mail_host, int mail_port, int encryptionType, boolean auth, String account, String password) {  
            this.mail_host = mail_host;  
            this.mail_port = mail_port;  
            this.encryptionType = encryptionType;  
            this.auth = auth;  
            this.mail_host_account = account;  
            this.mail_host_password = password;  
        }  
      
        public EmailUtil(String mail_host, boolean auth, String account, String password, boolean isHtml) {  
            this(mail_host, 25, EncryptionTypes.Default.ordinal(), auth, account, password, isHtml);  
        }  
      
        public EmailUtil(String mail_host, int mail_port, int encryptionType, boolean auth, String account, String password, boolean isHtml) {  
            this.mail_host = mail_host;  
            this.mail_port = mail_port;  
            this.encryptionType = encryptionType;  
            this.auth = auth;  
            this.mail_host_account = account;  
            this.mail_host_password = password;  
            this.isHtml = isHtml;  
        }  
      
        public void sendEmail(String senderAddress, String senderName, String receiverAddress, String sub, String msg) throws Exception {  
            String[] address = receiverAddress.split(";");  
            List recipients = new ArrayList();  
            for (int i = 0; i < address.length; i++) {  
                if (address[i].trim().length() > 0) {  
                    recipients.add(address[i]);  
                }  
            }  
            this.sendEmail(senderAddress, senderName, recipients, sub, msg);  
        }  
      
        public void sendEmail(String senderAddress, String senderName, List recipients, String sub, String msg) throws SendFailedException {  
            this.sendEmail(senderAddress, senderName, recipients, sub, msg, null);  
        }  
      
        public void sendEmail(String senderAddress, String senderName, String receiverAddress, String sub, String msg, Collection attachments) throws Exception {  
            String[] address = receiverAddress.split(";");  
            List recipients = new ArrayList();  
            for (int i = 0; i < address.length; i++) {  
                if (address[i].trim().length() > 0) {  
                    recipients.add(address[i]);  
                }  
            }  
            this.sendEmail(senderAddress, senderName, recipients, sub, msg, attachments);  
        }  
      
        public void sendEmailByProxy(String proxyHost, String proxyPort, String senderAddress, String senderName, String receiverAddress, String sub, String msg, Collection attachments) throws Exception {  
            String[] address = receiverAddress.split(";");  
            List recipients = new ArrayList();  
            for (int i = 0; i < address.length; i++) {  
                if (address[i].trim().length() > 0) {  
                    recipients.add(address[i]);  
                }  
            }  
            this.sendEmailByProxy(proxyHost, proxyPort, senderAddress, senderName, recipients, sub, msg, attachments);  
        }  
      
    	public void sendEmail(String senderAddress, String senderName,
    			List recipients, String sub, String msg, Collection attachments) throws SendFailedException {  
            Transport transport = null;  
            try {  
                Properties props = this.getProperties();  
                Session session = this.getSession(props);  
                MimeMessage message = new MimeMessage(session);  
                if (this.getDefaultIsHtml()) {  
                    message.addHeader("Content-type", "text/html");  
                } else {  
                    message.addHeader("Content-type", "text/plain");  
                }  
                message.setSubject(sub, default_charset);  
                message.setFrom(new InternetAddress(senderAddress, senderName));  
                for (Iterator it = recipients.iterator(); it.hasNext();) {  
                    String email = (String) it.next();  
                    message.addRecipients(Message.RecipientType.TO, email);  
                }  
                Multipart mp = new MimeMultipart();  
                MimeBodyPart contentPart = new MimeBodyPart();  
                if (this.getDefaultIsHtml()) {  
                    contentPart.setContent("<meta http-equiv=Content-Type content=text/html; charset=" + default_charset + ">" + msg, "text/html;charset=" + default_charset);  
                } else {  
                    contentPart.setText(msg, default_charset);  
                }  
                mp.addBodyPart(contentPart);  
                if (attachments != null) {  
                    MimeBodyPart attachPart;  
                    for (Iterator it = attachments.iterator(); it.hasNext();) {  
                        attachPart = new MimeBodyPart();  
                        FileDataSource fds = new FileDataSource(it.next().toString().trim());  
                        attachPart.setDataHandler(new DataHandler(fds));  
                        if (fds.getName().indexOf("$") != -1) {  
                            attachPart.setFileName(fds.getName().substring(fds.getName().indexOf("$") + 1, fds.getName().length()));  
                        } else {  
                            attachPart.setFileName(fds.getName());  
                        }  
                        mp.addBodyPart(attachPart);  
                    }  
                }  
                message.setContent(mp);  
                message.setSentDate(new Date());  
                if (this.getDefaultEncryptionType() == EncryptionTypes.SSL.ordinal()) {  
                    Transport.send(message);  
                } else {  
                    transport = session.getTransport("smtp");  
                    transport.connect(this.mail_host, this.mail_port, this.mail_host_account, this.mail_host_password);  
                    transport.sendMessage(message, message.getAllRecipients());  
                }  
            } catch (Exception e) {  
                logger.error("send mail error", e);  
                throw new SendFailedException(e.toString());  
            } finally {  
                if (transport != null) {  
                    try {  
                        transport.close();  
                    } catch (Exception ex) {  
                    }  
                }  
            }  
        }  
      
        public void sendEmailByProxy(String proxyHost, String proxyPort, String senderAddress, String senderName, List recipients, String sub, String msg, Collection attachments) throws SendFailedException {  
            Transport transport = null;  
            try {  
                Properties props = this.getProxyProperties(proxyHost, proxyPort);  
                Session session = this.getSession(props);  
                MimeMessage message = new MimeMessage(session);  
                if (this.getDefaultIsHtml()) {  
                    message.addHeader("Content-type", "text/html");  
                } else {  
                    message.addHeader("Content-type", "text/plain");  
                }  
                message.setSubject(sub, default_charset);  
                message.setFrom(new InternetAddress(senderAddress, senderName));  
                for (Iterator it = recipients.iterator(); it.hasNext();) {  
                    String email = (String) it.next();  
                    message.addRecipients(Message.RecipientType.TO, email);  
                }  
                Multipart mp = new MimeMultipart();  
                MimeBodyPart contentPart = new MimeBodyPart();  
                if (this.getDefaultIsHtml()) {  
                    contentPart.setContent("<meta http-equiv=Content-Type content=text/html; charset=" + default_charset + ">" + msg, "text/html;charset=" + default_charset);  
                } else {  
                    contentPart.setText(msg, default_charset);  
                }  
                mp.addBodyPart(contentPart);  
                if (attachments != null) {  
                    MimeBodyPart attachPart;  
                    for (Iterator it = attachments.iterator(); it.hasNext();) {  
                        attachPart = new MimeBodyPart();  
                        FileDataSource fds = new FileDataSource(it.next().toString().trim());  
                        attachPart.setDataHandler(new DataHandler(fds));  
                        if (fds.getName().indexOf("$") != -1) {  
                            attachPart.setFileName(fds.getName().substring(fds.getName().indexOf("$") + 1, fds.getName().length()));  
                        } else {  
                            attachPart.setFileName(fds.getName());  
                        }  
                        mp.addBodyPart(attachPart);  
                    }  
                }  
                message.setContent(mp);  
                message.setSentDate(new Date());  
                if (this.getDefaultEncryptionType() == EncryptionTypes.SSL.ordinal()) {  
                    Transport.send(message);  
                } else {  
                    transport = session.getTransport("smtp");  
                    transport.connect(this.mail_host, this.mail_port, this.mail_host_account, this.mail_host_password);  
                    transport.sendMessage(message, message.getAllRecipients());  
                }  
            } catch (Exception e) {  
                logger.error("send mail error", e);  
                throw new SendFailedException(e.toString());  
            } finally {  
                if (transport != null) {  
                    try {  
                        transport.close();  
                    } catch (Exception ex) {  
                    }  
                }  
            }  
        }  
      
        private Properties getProperties() {  
            Properties props = System.getProperties();  
            int defaultEncryptionType = this.getDefaultEncryptionType();  
            if (defaultEncryptionType == EncryptionTypes.TLS.ordinal()) {  
                props.put("mail.smtp.auth", String.valueOf(this.auth));  
                props.put("mail.smtp.starttls.enable", "true");  
            } else if (defaultEncryptionType == EncryptionTypes.SSL.ordinal()) {  
                props.put("mail.smtp.host", this.mail_host);  
                props.put("mail.smtp.socketFactory.port", this.mail_port);  
                props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");  
                props.put("mail.smtp.debug", "true");  
                props.put("mail.smtp.auth", String.valueOf(this.auth));  
                props.put("mail.smtp.port", this.mail_port);  
            } else {  
                props.put("mail.smtp.host", this.mail_host);  
                props.put("mail.smtp.auth", String.valueOf(this.auth));  
            }  
            return props;  
        }  
      
        // 设置代理服务器  
        private Properties getProxyProperties(String proxyHost, String proxyPort) {  
            Properties props = System.getProperties();  
            props.setProperty("proxySet", "true");  
            props.setProperty("socksProxyHost", proxyHost);  
            props.setProperty("socksProxyPort", proxyPort);  
            props.setProperty("mail.smtp.host", this.mail_host);  
            props.put("mail.smtp.auth", String.valueOf(this.auth));  
            props.put("mail.debug", "true");  
            return props;  
        }  
      
        private Session getSession(Properties props) {  
            Session session = null;  
            if (this.getDefaultEncryptionType() == EncryptionTypes.TLS.ordinal()) {  
                session = Session.getInstance(props);  
            } else if (this.getDefaultEncryptionType() == EncryptionTypes.SSL.ordinal()) {  
                session = Session.getInstance(props, new MyAuthenticator(this.mail_host_account, this.mail_host_password));  
            } else {  
                session = Session.getDefaultInstance(props, null);  
            }  
            return session;  
        }  
      
        private boolean getDefaultIsHtml() {  
            boolean rst = this.isHtml;  
            return rst;  
        }  
      
        private class MyAuthenticator extends Authenticator {  
            String user;  
            String password;  
      
            public MyAuthenticator() {  
            }  
      
            public MyAuthenticator(String user, String password) {  
                this.user = user;  
                this.password = password;  
            }  
      
            protected PasswordAuthentication getPasswordAuthentication() {  
                return new PasswordAuthentication(this.user, this.password);  
            }  
        }  
      
        private int getDefaultEncryptionType() {  
            int rst = this.encryptionType;  
            if (this.encryptionType == EncryptionTypes.Default.ordinal()) {  
                if (this.mail_port == 465) {  
                    rst = EncryptionTypes.SSL.ordinal();  
                } else if (this.mail_port == 587) {  
                    rst = EncryptionTypes.TLS.ordinal();  
                }  
            }  
            return rst;  
        }  
    } 

    调用实例

    /**
     * 
     * @param emailMap Map<receiverAddress,emailMessage>
     * receiverAddress 可以是以 ; 分割的多个邮箱地址字符串
     */
    private void sendEmail(Map emailMap) {
    	String senderAddress = "";// 发送人地址
    	String senderName = "Name";// 发送人名称
    	String mail_host = "";// 邮件host
    	String mail_port = "";// 发送端口
    	String account = "";// 账号
    	String password = "";// 密码
    	EmailUtil email = null;
    	try {
    		// 初始化邮件配置
    		String emailStr = "发送人邮箱host ip;25;account;password;senderAddress";
    		if (emailStr.length() > 0) {
    			String[] temp = emailStr.split(";");
    			mail_host = temp[0];//邮箱主机 ip
    			mail_port = temp[1];//邮箱端口
    			account = temp[2];//发送者邮箱账号
    			password = temp[3];//发送者邮箱密码
    			senderAddress = temp[4];//发送者邮箱地址
    			email = new EmailUtil(mail_host, Integer.parseInt(mail_port), 0, true, account, password, true);
    		}
    		if (email != null) {
    			StringBuffer sb;
    			for (Object emailAddr : emailMap.keySet()) {
    				sb = new StringBuffer();
    				sb.append("<html><head></head><body>");
    				sb.append(emailMap.get(emailAddr).toString());
    				sb.append("</body></html>");
    				email.sendEmail(senderAddress, senderName, emailAddr.toString(), "提醒:Name邮箱提醒",
    						sb.toString());
    			}
    
    		}
    	} catch (NumberFormatException e) {
    		e.printStackTrace();
    	} catch (Exception e) {
    		e.printStackTrace();
    	}
    
    }
  • 相关阅读:
    Spring Boot 配置元数据指南
    面试中常被提到的最左前缀匹配原则
    MyBatis缓存机制(一级缓存,二级缓存)
    计算机网络基础知识
    垃圾收集算法与垃圾收集器
    递归与分治策略
    五种IO模型和BIO,NIO,AIO
    七种阻塞队列
    ConcurrentHashMap(1.7版本和1.8版本)
    重入锁 ReentrantLock
  • 原文地址:https://www.cnblogs.com/pengguozhen/p/13992615.html
Copyright © 2011-2022 走看看