歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux編程 >> Linux編程

Java使用代理發送郵件

最近用java寫個發郵件的東東,然後打成jar包,jar包可以放在任何地方郵件正常發送

要求 :

1、網絡正常的情況下,可以發送;

2、網絡不正常的時候,需要使用內網連接到外網,使用代理發送郵件。

部分代碼拿出來分享一下:

package com.zyuc.mail;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import javax.activation.*;
import javax.mail.*;
import javax.mail.internet.*;
import org.apache.log4j.Logger;
import com.zyuc.domParse.DomParseXml;
import com.zyuc.util.UtilTools;

/**
 * 郵件發送
 * @author wangxw
 * 2011-10-26
 */
public class JmailConfig {
 
 private static Logger logger =  Logger.getLogger(JmailConfig.class);
 private static Map map = new HashMap();
 private static JmailFileRead jmailFileRead = new JmailFileRead();
 public  String Email_Text = new String();
 private static JmailConfig mail = new JmailConfig();
 
 /**
  *構造函數 初始化參數信息
  */
 public JmailConfig(){
  //獲得配置文件
  String configPath = UtilTools.getPath()+File.separator+"JmailConfig.xml";
  File file = new File(configPath);
  //加載配置文件信息
  if(file.exists()){
   map = new DomParseXml().parseXml(configPath);
   Email_Text = jmailFileRead.fileRead(map.get("Email_Text").toString());
  }else{
   logger.error("郵件配置文件未找到");
  }
 }
 
 /**
  * 郵件附件的添加
  * @param multipart
  * @param filePath
  * @param fileName
  * @param k
  * @return boolean
  */
 private boolean addMultipart(Multipart multipart, String filePath,
   String fileName, int k) {
  boolean flag = true;
  try {
   MimeBodyPart messageBodyPart = new MimeBodyPart();
   if (k == 0) {
    messageBodyPart.setText(Email_Text);
    multipart.addBodyPart(messageBodyPart);
   }
   messageBodyPart = new MimeBodyPart();
   DataSource source = new FileDataSource(filePath);
   messageBodyPart.setDataHandler(new DataHandler(source));
   messageBodyPart.setFileName(fileName);
   multipart.addBodyPart(messageBodyPart);
  } catch (Exception e) {
   flag = false;
   logger.error("郵件附件的添加失敗" + e.getMessage());
   e.printStackTrace();
  }
  return flag;
 }
 
 /**
  * 發送郵件信息配置
  * @return boolean
  */
 public boolean sendMail(){
  boolean sendFlag = true;
  final String username = map.get("Email_User").toString();
  final String password = map.get("Email_Pswd").toString();
 
  Session session;
  //獲得是否使用代理發送的標識
  String Email_Proxy_Flag = map.get("Email_Proxy_Flag").toString();
  if("1".equalsIgnoreCase(Email_Proxy_Flag)){
   //若Email_Proxy_Flag==1則使用代理發送
   try {
    Properties props = System.getProperties();
    props.put("mail.smtp.auth", "true");
    props.setProperty("proxySet", "true");
    props.setProperty("mail.stmp.host", map.get("Email_Host").toString());
    props.setProperty("http.proxyhost",map.get("Email_Proxy_Host").toString());
    props.setProperty("http.proxyport",map.get("Email_Proxy_Port").toString());
   
    session = Session.getDefaultInstance(props,
      new Authenticator() {
       protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
        return new javax.mail.PasswordAuthentication(
          username, password);
       }
      });
    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(map.get("Email_From").toString()));
  
    //多個接受者
    String[] to = map.get("Email_To").toString().split(";");
    if (to != null) {
     InternetAddress[] toAddress = new InternetAddress[to.length];
     for (int i = 0; i < to.length; i++) {
      toAddress[i] = new InternetAddress(to[i]);
     }
     message.addRecipients(Message.RecipientType.TO, toAddress);
    }
   
    //多個抄送者
    String[] cc = map.get("Email_Cc").toString().split(";");
    if (null != cc) {
     InternetAddress[] ccAddress = new InternetAddress[cc.length];
     for (int j = 0; j < cc.length; j++) {
      ccAddress[j] = new InternetAddress(cc[j]);
     }
     message.addRecipients(Message.RecipientType.CC, ccAddress);
    }
    message.setSubject(map.get("Email_Subject").toString());
   
   
    //附件功能
    Multipart multipart = new MimeMultipart();
    String[] filepath = map.get("FilePath").toString().split(";");
    String[] attachName =  map.get("AttachName").toString().split(";");
    if (null != filepath) {
     for (int k = 0; k < filepath.length; k++) {
      addMultipart(multipart, filepath[k], attachName[k], k);
     }
    } else if (null == filepath) {
     message.setText(Email_Text);
    }
    message.setContent(multipart);
   
    Transport transport = session.getTransport("smtp");
    transport.connect(map.get("Email_Host").toString(), username, password);
    transport.sendMessage(message, message.getAllRecipients());
    transport.close();
    } catch (Exception e) {
     sendFlag = false;
     logger.error("使用代理發送郵件出錯" + e.getMessage());
     e.printStackTrace();
    }
  }else{
   //若Email_Proxy_Flag!=1則不使用代理發送
   try {
    Properties props = System.getProperties();
    props.put("mail.smtp.auth", "true");
    props.setProperty("mail.stmp.host", map.get("Email_Host").toString());
   
    session = Session.getDefaultInstance(props,
      new Authenticator() {
       protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
        return new javax.mail.PasswordAuthentication(
          username, password);
       }
      });
    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(map.get("Email_From").toString()));
  
    //多個接收者
    String[] to = map.get("Email_To").toString().split(";");
    if (to != null) {
     InternetAddress[] toAddress = new InternetAddress[to.length];
     for (int i = 0; i < to.length; i++) {
      toAddress[i] = new InternetAddress(to[i]);
     }
     message.addRecipients(Message.RecipientType.TO, toAddress);
    }
   
    //多個抄送者
    String[] cc = map.get("Email_Cc").toString().split(";");
    if (null != cc && cc.length > 0) {
     InternetAddress[] ccAddress = new InternetAddress[cc.length];
     for (int j = 0; j < cc.length; j++) {
      ccAddress[j] = new InternetAddress(cc[j]);
     }
     message.addRecipients(Message.RecipientType.CC, ccAddress);
    }
    message.setSubject(map.get("Email_Subject").toString());
   
    //附件功能
    Multipart multipart = new MimeMultipart();
    String[] filepath = map.get("FilePath").toString().split(";");
    String[] attachName =  map.get("AttachName").toString().split(";");
    if (null != filepath && filepath.length > 0 && attachName.length > 0 && filepath.length == attachName.length) {
     for (int k = 0; k < filepath.length; k++) {
      addMultipart(multipart, filepath[k], attachName[k], k);
     }
    } else if (null == filepath) {
     message.setText(Email_Text);
    }
    message.setContent(multipart);
   
    Transport transport = session.getTransport("smtp");
    transport.connect(map.get("Email_Host").toString(), username, password);
    transport.sendMessage(message, message.getAllRecipients());
    transport.close();
   } catch (Exception e) {
    sendFlag = false;
    logger.error("發送郵件出錯" + e.getMessage());
    e.printStackTrace();
   }
  }
  return sendFlag;
 }
 
 public String returnMessage(){
  boolean flag = mail.sendMail();
  StringBuffer sb = new StringBuffer();
  if(flag){
   sb.append("\n").append("郵件發送已成功").append("\t").append("\n");
   sb.append("郵件發送者:" + map.get("Email_From").toString()).append("\t").append("\n");
   sb.append("郵件發送至:" + map.get("Email_To").toString()).append("\t").append("\n");
   sb.append("郵件抄送給:" + map.get("Email_Cc").toString()).append("\t").append("\n");
   sb.append("郵件正文為:" + map.get("Email_Text").toString()).append("\t").append("\n");
   sb.append("發送時間是:" + UtilTools.getDate()).append("\t").append("\n");
  }else{
   sb.append("\n").append("郵件發送失敗").append("\t").append("\n");
   sb.append("發送時間是:" + UtilTools.getDate()).append("\t").append("\n");
  }
  return sb.toString();
 }
 
 public static void main(String args[]) {
  logger.info("===============開始發送=================");
  logger.info(mail.returnMessage());
  logger.info("===============發送結束=================");
 }
}

Copyright © Linux教程網 All Rights Reserved