Java_Email


	/**
	 * 發送郵件
	 * @param req	HTTP伺服器請求
	 * @return HashMap 返回值	
	 * @throws Exception 
	 */	
	public HashMap sendEmail( HttpServletRequest req ) 	throws Exception		
	{			
		
		//返回值
		HashMap retMap = new HashMap();		
		//是否發送成功
		String ok_fail = "";
		//發送成功的郵件
		String validEmail = "";
		//發送失敗的郵件 
		String invalidEmail = "";
		//路徑
		String severPath = "http://" + req.getServerName() + ":" 
						  	+ req.getServerPort()+ req.getContextPath()+"/";		
		//圖片格式
		String imgStart = "<IMG SRC='" + severPath ;
		String imgSize1 = "' width=220 heigh=160 >";
		String imgSize2 = "' width=50 heigh=50 >";		
		
		//郵件以html格式發送,字符集為utf-8
		String htmlStart = 
			"<HTML><meta http-equiv=Content-Type content=text/html;charset=utf-8>";
		String htmlEnd = "</HTML>";		
		
		//取郵件服務器資料		
		ResourceBundle actionDB = ResourceBundle.getBundle("smtpdata");
		String SmtpServer= actionDB.getString("SmtpServer1");         
        String smtpUser = actionDB.getString("SmtpUser1"); 
        String SmtpPwd = actionDB.getString("SmtpPwd1"); 
		//經銷商為空時
		if ( "".equals(StringUtil.toStr(SessionUtil.getDealerId(req),"")) )
		{
			SmtpServer= actionDB.getString("SmtpServer2");         
	        smtpUser = actionDB.getString("SmtpUser2"); 
	        SmtpPwd = actionDB.getString("SmtpPwd2"); 				
		}
	     
        
        System.out.println("郵件服務器資料如下:");
        System.out.println("SmtpServer = "+SmtpServer);
        System.out.println("smtpUser = "+smtpUser);
        System.out.println("SmtpPwd = "+SmtpPwd);
        
		//取發送人地址
		String fromEmail = StringUtil.toStr(SessionUtil.getUserEmail(req));		
		//發信人名字
		String NickName = StringUtil.toStr(req.getParameter("NickName"));
		//取編號
		String EDrfnbr = StringUtil.toStr(req.getParameter("EDrfnbr"));
		//是否寄定期電子郵件
		String ESpaper = StringUtil.toStr(req.getParameter("ESpaper"));
		//取收件人地址			 
		String toEmails = emailCorrect(new String(req.getParameter("emailList")));		
		//取信件主旨
		String subject = StringUtil.toStr(req.getParameter("EStitle"));
		//取信件內容
		String Content = new String(req.getParameter("EScontent")).trim();
		//取圖片
		String ESpic =  StringUtil.toStr(req.getParameter("ESpic"));
		//取個人資訊
		String signature =  StringUtil.toStr(req.getParameter("signature"));
		//取附圖
		String pic = StringUtil.toStr(req.getParameter("pic"));
		//是否使用個人化TITLE		
		String PersonalizedTitle = StringUtil.toStr
										(req.getParameter("CkbPersonalizedTitle"));		
		PersonalizedTitle = "on".equals(PersonalizedTitle)?"Y":"N";	

		//如果有圖片
		ESpic = "".equals(ESpic)?"":imgStart + ESpic +  imgSize1;
		//如果有附圖		
		pic = "".equals(pic)?"":imgStart + pic +  imgSize2;		
		//附文
		String HContent ="<BR>" + ESpic + "<BR>" + signature + "<BR>" + pic +"<BR>";				
		//取屬性	
		Properties props = new Properties();
		//添加SMTP的服務器		
		props.put("mail.smtp.host", SmtpServer);
		props.put("mail.transport.protocol", "smtp");				
	
		//props.put("mail.smtp.connectiontimeout", "10000"); 
		//這是延時
		//props.put("mail.smtp.timeout", "10000");
		       
		//如果smtp有加驗證需要在后面加上true!
		props.put("mail.smtp.auth", "true");
		// 加驗證
		EmailAuthenticator auth = new EmailAuthenticator(smtpUser,  SmtpPwd);		 
		 
		//得到session的配置文件与驗證加進去
		javax.mail.Session sendMailSession = 
							javax.mail.Session.getDefaultInstance(props,auth);		
		
		//需要調試可以用下面的這行代碼
		//sendMailSession.setDebug(true);
		javax.mail.internet.MimeMessage msg = 
						new javax.mail.internet.MimeMessage(sendMailSession);
		//取得發送人地址
		javax.mail.internet.InternetAddress fromAddress = 
						new javax.mail.internet.InternetAddress(fromEmail);
		//設定發送人地址
		msg.setFrom(fromAddress);		
		//設定郵件發送日期
		msg.setSentDate(new java.util.Date());
		//設定郵件主題
		msg.setSubject( subject, "UTF-8");
		//建立
		javax.mail.Transport transport = sendMailSession.getTransport("smtp");
		try
		{			
			//連結
			transport.connect(SmtpServer, smtpUser, SmtpPwd);			
			//分解收件人地址
			String[] toAddress = toEmails.split(",");
			System.out.println("要發送的EMAIL共有: " +toAddress.length +" 個");
			System.out.println("發送的NAME和EMAIL如下: ");
			//循環發送
			for( int i=0; i< toAddress.length; i++ )
			{					
			    String toAddress_i = toAddress[i];			    
			    //分解姓名與email,並驗證是否為email
			    String[] nemail = name_email(toAddress_i);
			    String toName_i = nemail[0];
			    String toEmail_i = nemail[1];
			    System.out.println("NAME_"+i+" : "+toName_i);
			    System.out.println("EMAIL_"+i+" : "+toEmail_i);			    
			    //姓名與email相同,說明不是email地址
			    if ( toName_i.equals(toEmail_i) )
			    {
			    	invalidEmail += toAddress[i];
			    	invalidEmail += ",";
			    }
			    //如果是email地址
			    else
			    {
			    	//加入收件地址列
			    	msg.setRecipient(javax.mail.Message.RecipientType.TO,
			    			new javax.mail.internet.InternetAddress(toEmail_i));	   	
			    	String Content_1 = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + Content;			    	
			    	//如果是個人化TITLE
			    	if ( "Y".equals(PersonalizedTitle) )
			    	{
			    		//Dear {收信人}:
			    		String Ptitle = "Dear " + toName_i + ":<BR>" ;										
			    		Content_1 = Ptitle + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + Content;
			    	}					
			    	//郵件內容
			    	msg.setContent(htmlStart + Content_1 + HContent + htmlEnd,
			    							"text/html;charset=utf-8");
			    	// 保存
			    	msg.saveChanges();				
			    	// 發送
			    	try
			    	{			    		
			    		transport.send(msg);
						//更新成功郵件列表
			    		validEmail += toAddress[i];
			    		validEmail += ",";					
			    	}				    	
			    	//例外(email地址不存在時)
			    	catch (  SendFailedException e1)
			    	{					
			    		//更新失敗郵件列表
			    		invalidEmail += toAddress[i];	
			    		invalidEmail += ",";			    		
			    	}
			    }			    				
			  }
			//調整
			validEmail = emailCorrect(validEmail);
			invalidEmail = emailCorrect(invalidEmail);				
			//成功個數
			int validNum = "".equals(validEmail)?0:validEmail.split(",").length;
			//失敗個數
			int invalidNum = "".equals(invalidEmail)?0:invalidEmail.split(",").length;
			
			System.out.println("發送成功:"+validNum +" 個");
		    System.out.println("發送失敗"+invalidNum +" 個");
			
			System.out.println("發送成功的email:"+validEmail);
		    System.out.println("發送失敗的email"+invalidEmail);
			
			//如果全部失敗
			if ( invalidNum == toAddress.length )
			{
				ok_fail = "fail";
			}
			//如果有成功
			else 				
			{
				//全部成功
				if ( validNum == toAddress.length )				
					ok_fail = "ok";
				//部分成功
				else 
					ok_fail = "both";	
				
				//新增郵件發送記錄
				if ( insertData(req ,EDrfnbr,subject,Content, ESpaper, NickName) )
					System.out.println("信件寄送記錄表NS_EDM0427_SENDLOG新增成功!");
				else System.out.println("信件寄送記錄表NS_EDM0427_SENDLOG新增失敗!");				
			}		
		}		
		//例外
		catch( Exception e )
		{
			//設置返回值
			ok_fail = "auth_fail";		
			e.printStackTrace();
			throw e;					
		}
		//關閉連結,把值傳回
		finally
		{		
			transport.close();			
		}
		//返回值
		retMap.put("Mes",ok_fail);
		retMap.put("validEmail",replace(validEmail));
		retMap.put("invalidEmail",replace(invalidEmail));
		return retMap;
	}
	




以下代碼是郵件驗證時需用到的一個類:
package MyEmailTest;
import javax.mail.PasswordAuthentication;

/**
 * @author Administrator
 *
 */
public class MyAuthenticator  extends javax.mail.Authenticator 
{
    private String strUser;
    private String strPwd;
    public MyAuthenticator(String user, String password)
    {
      this.strUser = user;
      this.strPwd = password;
    }
    protected PasswordAuthentication getPasswordAuthentication()
    {
      return new PasswordAuthentication(strUser, strPwd);
    }
}


可參考: http://blog.csdn.net/herrapfel/archive/2007/11/06/1869823.aspx

你可能感兴趣的:(java,.net,Blog)