zoukankan      html  css  js  c++  java
  • Java网络编程:利用Java mail包发送电子邮件

    下面代码是利用Java mail包封装了一个发送邮件的类

    import java.io.File;
    import java.util.ArrayList;
    import java.util.Date;
    import java.util.List;
    import java.util.Properties;
    
    import javax.activation.DataHandler;
    import javax.activation.FileDataSource;
    import javax.mail.Message;
    import javax.mail.MessagingException;
    import javax.mail.Multipart;
    import javax.mail.Session;
    import javax.mail.Transport;
    import javax.mail.internet.AddressException;
    import javax.mail.internet.InternetAddress;
    import javax.mail.internet.MimeBodyPart;
    import javax.mail.internet.MimeMessage;
    import javax.mail.internet.MimeMultipart;
    
    public class SendMail {
        private static final String MAIL_ADDRESS_REGEX = "^[\w\.=-]+@[\w\.-]+\.[\w]{2,3}$";
    
        private String mailServer;
        private String sender;
        private String[] receiver;
    
        public SendMail(){
    
        }
    
        public void setMailBasicInfo(String mailServer,String sender,String receiver){
            this.mailServer = mailServer;
            this.sender = sender;
            this.receiver =receiver.split(",");
        }
    
        public void setMailBasicInfo(String mailServer,String sender,String[] users){
            this.mailServer = mailServer;
            this.sender = sender;
            this.receiver = users;
        }
    
        public void setMailBasicInfo(String mailServer,String sender,List<String> users){
            this.mailServer = mailServer;
            this.sender = sender;
            this.receiver = new String[users.size()];
            users.toArray(this.receiver);
        }
    
        public boolean send(String subject, String content, List<String> fileNames)
        {
            subject = subject==null?"":subject;
            content = content==null?"":content;
            Properties props = new Properties();
            props.put("mail.smtp.host", mailServer);
            Session session = Session.getInstance(props, null);
            try
            {
                InternetAddress[] receiver = getReceiverList();
                if (receiver.length == 0)
                {
                    System.out.println("receiver is null");
                    return false;
                }
                MimeMessage msg = new MimeMessage(session);
                msg.setFrom(new InternetAddress(sender));
                msg.setRecipients(Message.RecipientType.TO, receiver);
                msg.setSubject(subject);
                msg.setSentDate(new Date());
    
                Multipart container = new MimeMultipart();
                MimeBodyPart textBodyPart = new MimeBodyPart();
                textBodyPart.setContent(content.toString(), "text/html;charset=gbk");
                container.addBodyPart(textBodyPart);
    
                doAttachFile(container,fileNames);
                msg.setContent(container);
                System.out.println("begin send mail");
                Transport.send(msg);
                System.out.println("send mail success");
            }
            catch (MessagingException e)
            {
                System.out.println("send mail fail");
                System.out.println(e);
                return false;
            }
            catch(Exception e){
                return false;
            }
            return true;
        }
    
        public boolean send(String subject, String content){
            return send(subject,content,null);
        }
    
        public boolean send(String subject){
            return send(subject,null);
        }
    
        private void doAttachFile(Multipart container, List<String> fileNames) throws MessagingException{
            if(fileNames==null || fileNames.size()==0)
                return;
            for(String filename:fileNames){
                File f = new File(filename);
                if(!f.isFile())
                    continue;
                System.out.println("the attach file is:"+filename);
                MimeBodyPart fileBodyPart = new MimeBodyPart();
                FileDataSource fds = new FileDataSource(f);// 要发送的附件地址
                fileBodyPart.setDataHandler(new DataHandler(fds));
                fileBodyPart.setFileName(fds.getName());// 设置附件的名称
                container.addBodyPart(fileBodyPart);
            }
        }
    
        private InternetAddress[] getReceiverList() throws AddressException
        {
            ArrayList<InternetAddress> toList = new ArrayList<InternetAddress>();
            for (int i = 0; i < receiver.length; ++i)
            {
                if (receiver[i].matches(MAIL_ADDRESS_REGEX))
                {
                    toList.add(new InternetAddress(receiver[i]));
                }
            }
    
            return (InternetAddress[]) toList.toArray(new InternetAddress[toList.size()]);
        }
    }

    使用举例

    String host = "168.xx.xx.xx"; //邮件服务器的地址
    String subject = "发送邮件的主题";
    String sender = "test@gmail.com";
    List<String> receivers = new ArrayList<String>();
    receivers.add("user1@263.com");
    receivers.add("user2@263.com");
    String content = "邮件主题";
    SendMail sendMail = new SendMail();
    sendMail.setMailBasicInfo(host, sender, receivers);
    sendMail.send(subject, content, null); //没有附件
    
    正文也可以是html内容,如
    String content = "<html>详细信息:<a href='xxxx'>请点击查看!</a></html>";
     
  • 相关阅读:
    8 -- 深入使用Spring -- 5...3 使用@CacheEvict清除缓存
    8 -- 深入使用Spring -- 5...2 使用@Cacheable执行缓存
    tomcat 的 server.xml配置文件
    WEB-INF目录与META-INF目录的作用
    一个tomcat设置多个端口,多个端口对应多个应用
    8 -- 深入使用Spring -- 5...1 启用Spring缓存
    8 -- 深入使用Spring -- 5... Spring 3.1 新增的缓存机制
    8 -- 深入使用Spring -- 4...6 AOP代理:基于注解的XML配置文件的管理方式
    eclipse中设置文件的编码格式为utf-8
    MySQL 触发器简单实例
  • 原文地址:https://www.cnblogs.com/51kata/p/5123203.html
Copyright © 2011-2022 走看看