邮件代码整理

1.解决中文乱码
           testMessage.setSubject(subject,"gbk");
           testMessage.setText(messageText,"gbk");
2.避免发件人session获取失败
Session mailSession = Session.getDefaultInstance(props, sa);
换成://解决中文乱码和发送需要用户session
  Session mailSession = Session.getInstance(props, sa)
3.收件人以群组形式:
testMessage.addRecipients(javax.mail.Message.RecipientType.TO,
              toAddresss);
其中toAddresss是string类型数组
4.用httpClient处理用户请求

public class DealHttpUrl {

static Logger logger = Logger.getLogger(DealHttpUrl.class.getName());

/**
* 拼手机发送URL,并进行发送
* @param data
*/
public  void dealUrl(String mess,String key,String src,String fee,String dest ) throws Exception
{
mess = URLEncoder.encode(mess, "GBK");
System.out.println(mess);
String url = "http://ppt.sohu-inc.com/ppp/sns.php?mess="+mess+"&key=x1@9eng"+"&src="+src+"&fee="+fee+"&dest="+dest;
logger.info("Connecting to: " + url);
HttpClient httpClient = new HttpClient();
GetMethod getMethod = new GetMethod(url);
getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
try {
int statusCode = httpClient.executeMethod(getMethod);
if (statusCode != HttpStatus.SC_OK) {
logger.fatal("Method failed: " + getMethod.getStatusLine());
}
String s = getMethod.getResponseBodyAsString();
logger.info(s);

} catch (Exception e) {
logger.fatal("send mobile message failed![ " + url + " ]");
throw new Exception(url);
}finally{
getMethod.releaseConnection();
}

}



public static void main(String[] args){

String str = "http://ppt.sohu-inc.com/ppp/sns.php?mess=sftesat&key=x1@9eng&src=18601159680&fee=18601159680&dest=18601159680";
try {
//dealUrl("pig","x1@9eng","18601159680","18601159680","18601159680");
new DealHttpUrl().dealUrl("test","x1@9eng","18618361821","18618361821","18618361821");
System.out.println("---dealUrl success---");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


}

你可能感兴趣的:(httpclient,邮件)