jimingminlovefly

          統計

          最新評論

          案例-java發送QQ郵件

          package com.icicle.framework.member.server.util;

          import java.io.BufferedInputStream;
          import java.io.ByteArrayOutputStream;
          import java.io.FileInputStream;
          import java.io.IOException;
          import java.io.InputStream;
          import java.io.UnsupportedEncodingException;
          import java.util.Date;
          import java.util.LinkedHashMap;
          import java.util.Map;
          import java.util.Properties;

          import javax.activation.DataHandler;
          import javax.activation.FileTypeMap;
          import javax.mail.Authenticator;
          import javax.mail.Message;
          import javax.mail.MessagingException;
          import javax.mail.Multipart;
          import javax.mail.PasswordAuthentication;
          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 javax.mail.internet.MimeUtility;

          import org.apache.commons.lang.StringUtils;
          import org.apache.log4j.Logger;

          import com.icicle.framework.member.client.SendingEmailEnvelope;
          import com.icicle.framework.member.client.SendingEmailEnvelope.Attachment;

          public class SendingEmailUtilImpl implements SendingEmailUtil{

           
           private static final Logger logger = Logger.getLogger(SendingEmailUtilImpl.class);
           private String host;
           private String emailUser;
           private String displayUserName;
           private String password;
           private String port;
           
           protected String switcher;
           
           private MessageTemplate emailSubjectTemplate;
           private MessageTemplate emailContentTemplate;
           
           @Override
           public void sendEmail(SendingEmailEnvelope envelope)
             throws MessagingException {
            
            logger.debug("Sending Subject" + envelope.getSubject());
            logger.debug("Sending Message " + envelope.getContent());
            
            if (envelope.getRecipients().size() == 0 ) {
             logger.error("List of recipients is null");
             return;
            }

            Properties props = new Properties();
            /**自己郵件服務器配置
            props.setProperty("mail.transport.protocol", "smtp");
            props.setProperty("mail.host", host);
            props.setProperty("mail.user", emailUser);
            props.setProperty("mail.password", password);
            */
                  //QQ郵件服務器
            props.put("mail.smtp.host", host);
            props.put("mail.smtp.port",port );
            props.put("mail.smtp.starttls.enable","true" );
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.socketFactory.port", port);
            props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            props.put("mail.smtp.socketFactory.fallback", "false");
               
            props.setProperty("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            props.setProperty("mail.imap.socketFactory.fallback", "false");
            props.setProperty("mail.imap.port", "993");
            props.setProperty("mail.imap.socketFactory.port", "993");

            // switcher
            if(switcher != null && switcher.equals("on")){
            
             //Session mailSession = Session.getDefaultInstance(props, null);//自己郵件服務不需要驗證
             //QQ郵件服務器,需要驗證
             Session mailSession = Session.getDefaultInstance(props,new Authenticator(){
                  @Override
                  protected PasswordAuthentication getPasswordAuthentication() {
                     // TODO Auto-generated method stub
                     return new PasswordAuthentication(emailUser, password);
                  }
                  });
             /**替換QQ郵件服務器時注釋
             Transport transport = null; 
             transport = mailSession.getTransport();
                  */
             MimeMessage message = new MimeMessage(mailSession);
             message.setFrom(new InternetAddress(displayUserName + "<" + emailUser + ">"));
             message.setSentDate(new Date());
             try {
              message.setSubject(MimeUtility.encodeText(envelope.getSubject(), "UTF-8", "B"));
             } catch (UnsupportedEncodingException e) {
              logger.error("", e);
             }
             
             Multipart multipart = new MimeMultipart();
             MimeBodyPart messageBodyPart = new MimeBodyPart();

             messageBodyPart.setContent(envelope.getContent(), "text/html; charset=\"UTF-8\"");
             messageBodyPart.setHeader("Content-Type", "text/html; charset=\"UTF-8\"");
             messageBodyPart.setHeader("Content-Transfer-Encoding", "base64");
             
             multipart.addBodyPart(messageBodyPart);
             
             if(envelope.getAttachments() != null){
              logger.debug("Sending Attachments " + envelope.getAttachments().size()); 
              for(Attachment attachment : envelope.getAttachments()){
               String fileName = attachment.getName();
               byte[] bytes = attachment.getFile();
               logger.debug("Sending Attached file " + fileName); 
               if(StringUtils.isEmpty(fileName) ||
                 bytes == null || bytes.length == 0){
                continue;
               }
               MimeBodyPart attachmentBodyPart = new MimeBodyPart();
               attachmentBodyPart.setFileName(fileName);
               ByteArrayDataSource dataSource = new ByteArrayDataSource();
               dataSource.setName(fileName);
               dataSource.setBytes(bytes);
               String contentType =
                FileTypeMap.getDefaultFileTypeMap().getContentType(fileName);
               dataSource.setContentType(contentType);
               logger.info(new StringBuilder()
                 .append("FileName: ").append(fileName)
                 .append(" ContentType: ").append(contentType));
               attachmentBodyPart.setDataHandler(new DataHandler(dataSource));
               multipart.addBodyPart(attachmentBodyPart);
              } 
             }
             message.setContent(multipart);
             
             if(envelope.getRecipients() != null){
              for (String recipient : envelope.getRecipients()) {
               if (recipient != null && !recipient.trim().equals("")) {
                logger.warn("Ready to send emails to recipient '" + recipient + "'.");
                message.addRecipient(Message.RecipientType.TO,
                  new InternetAddress(recipient));
               }
              }    
             }
             
             if(envelope.getCc() != null){
              for (String recipient : envelope.getCc()) {
               if (recipient != null && !recipient.trim().equals("")) {
                logger.warn("Ready to send emails to Cc '" + recipient + "'.");
                message.addRecipient(Message.RecipientType.CC,
                  new InternetAddress(recipient));
               }
              }    
             }

             if(envelope.getBcc() != null){
              for (String recipient : envelope.getBcc()) {
               if (recipient != null && !recipient.trim().equals("")) {
                logger.warn("Ready to send emails to Bcc '" + recipient + "'.");
                message.addRecipient(Message.RecipientType.BCC,
                  new InternetAddress(recipient));
               }
              }    
             }
             
             if (message.getAllRecipients() != null &&
               message.getAllRecipients().length != 0) {
              try {
               logger.info("Sending message.");
               /**
               transport.connect();替換QQ郵件服務器時注釋
               transport.sendMessage(message,
                 message.getAllRecipients());
                 */
               Transport.send(message,message.getAllRecipients());
               logger.info("Message sent.");
              } finally {
               //transport.close();
              }
             } else {
              logger.error("List of recipients is null");
              return;
             }
            }
           }

           public void sendEmail(String subject, String content,
             Map<String, byte[]> attachments, Boolean preview, String... recipients )
             throws MessagingException {
            SendingEmailEnvelope envelope = new SendingEmailEnvelope();
            envelope.setSubject(subject);
            envelope.setContent(content);
            envelope.addRecipients(recipients);
            if (attachments != null) {
             for (String name : attachments.keySet()) {
              byte[] file = attachments.get(name);
              envelope.addAttachment(name, file);
             }
            }
            if(StringUtils.isNotBlank(content) && preview == false){
             sendEmail(envelope); 
            }
           }

           @Override
           public SendingEmailEnvelope sendEmail(String subject, String templateName, Object[] args,
             Map<String, byte[]> attachments, Boolean preview, String... recipients) throws MessagingException {
            String subTemp = emailSubjectTemplate.getTemplate(subject, args);
            if(subTemp != null){
             subject = subTemp;
            }
            String content = emailContentTemplate.getTemplate(templateName, args);
            
            SendingEmailEnvelope envelope = new SendingEmailEnvelope();
            envelope.setSubject(subject);
            envelope.setContent(content);
            envelope.addRecipients(recipients);
            if(attachments != null){
             for(String name : attachments.keySet()){
              byte[] file = attachments.get(name);
              envelope.addAttachment(name, file);
             }   
            }
            if(StringUtils.isNotBlank(content) && preview == false){
             this.sendEmail(envelope);
            }
            return envelope;
           }

           public void setHost(String host) {
            this.host = host;
           }

           public void setEmailUser(String emailUser) {
            this.emailUser = emailUser;
           }

           public void setDisplayUserName(String displayUserName) {
            this.displayUserName = displayUserName;
           }

           public void setPassword(String password) {
            this.password = password;
           }

           public void setEmailSubjectTemplate(MessageTemplate emailSubjectTemplate) {
            this.emailSubjectTemplate = emailSubjectTemplate;
           }

           public void setEmailContentTemplate(MessageTemplate emailContentTemplate) {
            this.emailContentTemplate = emailContentTemplate;
           }

           public MessageTemplate getEmailSubjectTemplate() {
            return emailSubjectTemplate;
           }

           public MessageTemplate getEmailContentTemplate() {
            return emailContentTemplate;
           }

           public String getPort() {
            return port;
           }

           public void setPort(String port) {
            this.port = port;
           }

           public void setSwitcher(String switcher) {
            this.switcher = switcher;
           }

           public static void main(String[] args) throws MessagingException, IOException{
            System.out.println("-----send eMial start-----");
            SendingEmailUtilImpl email = new SendingEmailUtilImpl();
            email.setHost("smtp.exmail.qq.com");
            email.setEmailUser("cs@517hk.com");
            email.setPassword("szyl517hk");
            email.setPort("465");
            email.setDisplayUserName("517HK Customer Service");
            email.setSwitcher("on");
            
            SendingEmailEnvelope envelope = new SendingEmailEnvelope();
            envelope.setSubject("hello");
            envelope.setContent("hello");
            envelope.addRecipients("82067130@qq.com","45424380@qq.com");
            email.sendEmail(envelope);
            System.out.println("-----send eMial end-----");
            
          //  Map<String, byte[]> attachments = new LinkedHashMap<String, byte[]>();
          //  InputStream in = new BufferedInputStream(new FileInputStream("C:\\temp\\HotelXo.pdf"));
          //  ByteArrayOutputStream out = new ByteArrayOutputStream();
          //  try{
          //   byte[] buffer = new byte[512];
          //   int len = in.read(buffer);
          //   while(len >= 0){
          //    out.write(buffer, 0, len);
          //    len = in.read(buffer);
          //   }
          //   attachments.put("HotelXo.pdf",  out.toByteArray());
          //   email.sendEmail("hello", "Hello World.", null, "charles.so@222m.net");   
          //  }finally{
          //   in.close();
          //   out.close();
          //  }

           }
           
          }

          posted on 2011-11-04 16:56 計明敏 閱讀(4640) 評論(4)  編輯  收藏 所屬分類: java

          評論

          # re: 案例-java發送QQ郵件 2013-11-06 13:44

          深入溝通過  回復  更多評論   

          # re: 案例-java發送QQ郵件 2014-12-30 18:32 薩芬

          安撫的  回復  更多評論   

          # re: 案例-java發送QQ郵件[未登錄] 2016-05-07 23:36 af

          fadsfsdafsdd  回復  更多評論   

          # re: 案例-java發送QQ郵件[未登錄] 2016-05-07 23:37 af

          dafasdfasdfaffffffffffffffffffffffffffffffffffff  回復  更多評論   

          主站蜘蛛池模板: 醴陵市| 奉新县| 晋州市| 龙胜| 咸阳市| 盘锦市| 徐水县| 横峰县| 元江| 恩施市| 平凉市| 吐鲁番市| 信丰县| 商丘市| 禄丰县| 兴海县| 贵阳市| 若尔盖县| 邻水| 岐山县| 余干县| 铜山县| 灵武市| 陆河县| 绥宁县| 洞头县| 循化| 崇信县| 聊城市| 万荣县| 白沙| 奉新县| 丽江市| 绥芬河市| 罗平县| 永和县| 兰考县| 深圳市| 墨竹工卡县| 天峨县| 囊谦县|