使用ESMTP(SMTP)進行郵件發送
2024-07-21 02:14:05
供稿:網友
 
使用esmtp/smtp進行郵件發送,遇到一個問題:
假如附件為圖片gif文件,發送沒有問題。但是接收后,無法顯示圖片。敬請高手指點!!!!!
/*
 * created on 2004-12-21
 *
 * todo to change the template for this generated file go to
 * window - preferences - java - code style - code templates
 */
/**
 * @author administrator
 *
 * todo to change the template for this generated type comment go to
 * window - preferences - java - code style - code templates
 */
public class foxmailmain {
 public static void main(string[] args) {
 
 foxmail foxmail = new foxmail("smtp.citiz.net",25);
 foxmail.setmailusername("zhou");
 foxmail.setmailuserpass("abcdefgf");
 foxmail.setmailto("[email protected]");
 foxmail.setmailfrom("[email protected]");
 foxmail.setmailshowto("tom");
 foxmail.setmailshowfrom("nike");
 foxmail.setmailsubject("hello用中文主題");
 foxmail.setmailbody("welcome for you. mmm.中文呀.aaa /r/n載來一行");
 foxmail.setmailattachfile(new string[] {"d://eclipse_project//workspace//project_email//src//pic.gif"});
 
 if(foxmail.sendmail()){
 system.out.println("ok.");
 }else{
 system.out.println("false.");
 }
 }
}
foxmail.java 代碼
import java.io.file;
import java.io.fileinputstream;
import java.io.filenotfoundexception;
import java.io.ioexception;
import java.io.inputstream;
import java.io.outputstream;
import java.net.socket;
import java.text.dateformat;
import java.text.simpledateformat;
import java.util.date;
/*
 * created on 2004-12-21
 *
 * todo to change the template for this generated file go to
 * window - preferences - java - code style - code templates
 */
/**
 * @author administrator
 *
 * todo to change the template for this generated type comment go to
 * window - preferences - java - code style - code templates
 */
public class foxmail {
 
 private final static byte location_to_screen = 1;//log信息輸出位置 1=輸出到屏幕
 private final static dateformat dateformat = new simpledateformat("yyyy-mm-dd hh:mm:ss");//日志用日期格式
 private final static string end_flag = "/r/n";//smtp/esmtp命令結束標記
 private final static string email_attach_sign = "=====att";//郵件附件的表示符號
 private string smtpserver = null;//郵件發送服務器域名
 private int smtpport = 25;//郵件發送端口
 private socket clientmailsocket;//郵件連接socket
 private inputstream indata;//接收數據 
 private outputstream outdata;//發送數據
 private string mailusername = null;//郵件賬戶
 private string mailuserpass = null;//郵件賬戶的密碼
 private string mailto = null;//郵件發送目標
 private string mailfrom = null;//郵件發送人
 private string mailsubject = null;//郵件主題
 private string mailbody = null;//郵件正文 
 private string mailshowto = null;//郵件內容抬頭部分-郵件發送目標
 private string mailshowfrom = null;//郵件內容抬頭部分-郵件發送人
 private string[] mailattachfile = null;//郵件附件對應的本地文件名(包含絕對路徑)
 
 /**
 * @return returns the mailattachfile.
 */
 public string[] getmailattachfile() {
 return mailattachfile;
 }
 /**
 * @param mailattachfile the mailattachfile to set.
 */
 public void setmailattachfile(string[] mailattachfile) {
 this.mailattachfile = mailattachfile;
 }
 /**
 * @return returns the mailshowfrom.
 */
 public string getmailshowfrom() {
 return mailshowfrom;
 }
 /**
 * @param mailshowfrom the mailshowfrom to set.
 */
 public void setmailshowfrom(string mailshowfrom) {
 this.mailshowfrom = mailshowfrom;
 }
 /**
 * @return returns the mailshowto.
 */
 public string getmailshowto() {
 return mailshowto;
 }
 /**
 * @param mailshowto the mailshowto to set.
 */
 public void setmailshowto(string mailshowto) {
 this.mailshowto = mailshowto;
 }
 
 /**
 * @return returns the mailbody.
 */
 public string getmailbody() {
 return mailbody;
 }
 /**
 * @param mailbody the mailbody to set.
 */
 public void setmailbody(string mailbody) {
 this.mailbody = mailbody;
 }
 /**
 * @return returns the mailfrom.
 */
 public string getmailfrom() {
 return mailfrom;
 }
 /**
 * @param mailfrom the mailfrom to set.
 */
 public void setmailfrom(string mailfrom) {
 this.mailfrom = mailfrom;
 }
 /**
 * @return returns the mailsubject.
 */
 public string getmailsubject() {
 return mailsubject;
 }
 /**
 * @param mailsubject the mailsubject to set.
 */
 public void setmailsubject(string mailsubject) {
 this.mailsubject = mailsubject;
 }
 /**
 * @return returns the mailto.
 */
 public string getmailto() {
 return mailto;
 }
 /**
 * @param mailto the mailto to set.
 */
 public void setmailto(string mailto) {
 this.mailto = mailto;
 }
 /**
 * @return returns the mailusername.
 */
 public string getmailusername() {
 return mailusername;
 }
 /**
 * @param mailusername the mailusername to set.
 */
 public void setmailusername(string mailusername) {
 this.mailusername = mailusername;
 }
 /**
 * @return returns the mailuserpass.
 */
 public string getmailuserpass() {
 return mailuserpass;
 }
 /**
 * @param mailuserpass the mailuserpass to set.
 */
 public void setmailuserpass(string mailuserpass) {
 this.mailuserpass = mailuserpass;
 }
 /**
 * constrctor
 * @param _smtpserver
 * @param _smtpport
 */
 public foxmail(string smtpserver,int smtpport){
 this.smtpserver = smtpserver;
 this.smtpport = smtpport;
 }
 
 
 /**
 * 寫日志信息
 * @param _log
 * @param _locaton
 */
 public static void printlogger(string _log,int _locaton){
 switch(_locaton){
 case location_to_screen:
 system.out.println("["+dateformat.format(new date()) + "] " + _log);
 break;
 default:
 system.out.println("["+dateformat.format(new date()) + "] " + _log);
 }//switch(_locaton)
 }//end
 
 /**
 * 
 * @return
 */
 public boolean createconnection(){
 try {
 freeall();
 clientmailsocket = new socket(smtpserver, smtpport);
 printlogger("connect to email server " + smtpserver + " on port " + smtpport,location_to_screen);
 indata = clientmailsocket.getinputstream();
 outdata = clientmailsocket.getoutputstream();
 fetchcmdresult();//當首次連接服務器后有返回值,必須取走該返回值,否則后面命令的返回值無法判斷
 } catch (ioexception e) {
 return false;
 }
 return true;
 }
 
 public static string response(inputstream in){
 byte[] buffer = new byte[1024];
 stringbuffer indata = new stringbuffer();
 int n = 0;
 try {
 n = in.read(buffer);
 indata.append(new string(buffer, 0, n));
 
 } catch (ioexception e) {
 // todo auto-generated catch block
 e.printstacktrace();
 }
 printlogger("cmdresult=" + indata.tostring(),location_to_screen);
 return indata.tostring();
 }
 
 public static void send(string s, outputstream out){
 byte[] buffer = s.getbytes();
 try {
 out.write(buffer);
 out.flush();
 } catch (ioexception e) {
 // todo auto-generated catch block
 e.printstacktrace();
 }
 }
 public string fetchcmdresult(){
 return response(indata);
 }
 
 public boolean sendcmd(string _cmd) {
 if (_cmd != null) {
 send(_cmd,outdata);
 printlogger("cmd=" + _cmd,location_to_screen);
 }
 return true;
 }
 
 /**
 * 發送郵件
 * 服務器為esmtp時候采用本方法
 * @return true=send ok,false=send failed
 */
 public boolean sendmail() {
 
 //打開與郵件服務器的連接
 if(!createconnection()){
 return false;
 }
 
 stringbuffer thecontent = null;
 //ehlo
 thecontent = new stringbuffer();
 thecontent.append("ehlo ");
 thecontent.append(smtpserver);
 thecontent.append(end_flag);
 sendcmd(thecontent.tostring());
 if(fetchcmdresult().indexof("250")==-1) return false;
 //auth login
 thecontent = new stringbuffer();
 thecontent.append("auth login");
 thecontent.append(end_flag);
 sendcmd(thecontent.tostring());
 if(fetchcmdresult().indexof("334")==-1) return false;
 //用戶名
 thecontent = new stringbuffer();
 thecontent.append(base64encode(this.mailusername));
 thecontent.append(end_flag);
 sendcmd(thecontent.tostring());
 if(fetchcmdresult().indexof("334")==-1) return false;
 //密碼
 thecontent = new stringbuffer();
 thecontent.append(base64encode(this.mailuserpass));
 thecontent.append(end_flag);
 sendcmd(thecontent.tostring());
 if(fetchcmdresult().indexof("235")==-1) return false;
 //郵件發送者
 thecontent = new stringbuffer();
 thecontent.append("mail from:");
 thecontent.append("<");
 thecontent.append(this.mailfrom);
 thecontent.append(">");
 thecontent.append(end_flag);
 sendcmd(thecontent.tostring());
 if(fetchcmdresult().indexof("250")==-1) return false;
 //郵件發送目標地址
 thecontent = new stringbuffer();
 thecontent.append("rcpt to:");
 thecontent.append("<");
 thecontent.append(this.mailto);
 thecontent.append(">");
 thecontent.append(end_flag);
 sendcmd(thecontent.tostring());
 if(fetchcmdresult().indexof("250")==-1) return false;
 
 //郵件內容-開始
 thecontent = new stringbuffer();
 thecontent.append("data");
 thecontent.append(end_flag);
 sendcmd(thecontent.tostring());
 if(fetchcmdresult().indexof("354")==-1) return false;
 //郵件內容-郵件抬頭部分
 thecontent = new stringbuffer();
 thecontent.append("from:");
 thecontent.append(this.mailshowfrom);
 thecontent.append(end_flag);
 thecontent.append("to:");
 thecontent.append(this.mailshowto);
 thecontent.append(end_flag);
 thecontent.append("subject:");
 thecontent.append(this.mailsubject);
 thecontent.append(end_flag);
 thecontent.append("mime-version: 1.0");
 thecontent.append(end_flag);
 
 thecontent.append("content-type: multipart/mixed;boundary=/"");//設置附件表示符
 thecontent.append(email_attach_sign);
 thecontent.append("/"");
 thecontent.append(end_flag);//在正文內容前必須有2個end_flag標記
 thecontent.append(end_flag);
 sendcmd(thecontent.tostring());
 //郵件內容-正文部分
 thecontent = new stringbuffer();
 thecontent.append("--");
 thecontent.append(email_attach_sign);
 thecontent.append(end_flag);
 thecontent.append("content-type:text/plain;");
 thecontent.append(end_flag);
 thecontent.append("content-transfer-encoding: base64");
 thecontent.append(end_flag);
 thecontent.append(end_flag);
 thecontent.append(base64encode(this.mailbody));
 thecontent.append(end_flag);
 thecontent.append(end_flag);
 sendcmd(thecontent.tostring());
 
 //郵件內容-附件部分
 //mailattachfile = null;
 if(mailattachfile!=null && mailattachfile.length>0){
 for(int i=0;i<this.mailattachfile.length;i++){
 //發送附件抬頭
 thecontent = new stringbuffer();
 thecontent.append("--");
 thecontent.append(email_attach_sign);
 thecontent.append(i);
 thecontent.append(end_flag);
 thecontent.append("content-type:image/gif;name=/"aaa.gif/"");
 thecontent.append(end_flag);
 thecontent.append("content-transfer-encoding:base64");
 thecontent.append(end_flag);
 thecontent.append("content-disposition:attachment;name=/"aaa.gif/"");
 thecontent.append(end_flag);
 thecontent.append(end_flag);
 sendcmd(thecontent.tostring());
 
 //發送附件內容
 sendbase64data(new stringbuffer(base64encode(readfile(mailattachfile[i]))));
 
 //發送附件結束
 /*
 thecontent = new stringbuffer();
 thecontent.append(end_flag);
 thecontent.append("--");
 thecontent.append(email_attach_sign);
 thecontent.append(i);
 thecontent.append("--");
 thecontent.append(end_flag);
 sendcmd(thecontent.tostring());
 */
 }
 
 }
 
 
 //發送附件結束
 thecontent = new stringbuffer();
 thecontent.append(end_flag);
 thecontent.append(end_flag);
 thecontent.append("--");
 thecontent.append(email_attach_sign);
 thecontent.append("--");
 thecontent.append(end_flag);
 sendcmd(thecontent.tostring());
 
 //郵件內容-結束標記
 thecontent = new stringbuffer();
 thecontent.append(end_flag);
 thecontent.append(".");
 thecontent.append(end_flag);
 sendcmd(thecontent.tostring());
 if(fetchcmdresult().indexof("250")==-1) return false;
 
 //退出斷開服務器連接
 thecontent = new stringbuffer();
 thecontent.append("quit");
 thecontent.append(end_flag);
 sendcmd(thecontent.tostring());
 fetchcmdresult();
 
 //郵件發送成功后釋放資源
 freeall();
 thecontent = null;
 
 return true;//郵件發送成功
 }
 
 /**
 * 發送經過base64編碼后的數據
 * @param src
 */
 public void sendbase64data(stringbuffer srcdata){
 int len_cmd_data = 76;
 int startindex = 0;
 int totallength = 0;
 if(srcdata!=null && srcdata.length()>0){
 totallength = srcdata.length();
 while(true){
 if(startindex+len_cmd_data<totallength){
 sendcmd(srcdata.substring(startindex,startindex+len_cmd_data));
 sendcmd(end_flag);
 }else{
 sendcmd(srcdata.substring(startindex,totallength));
 sendcmd(end_flag);
 break;
 }
 startindex = startindex+len_cmd_data;
 }
 }
 }
 
 /**
 * 釋放所有資源
 *
 */
 public void freeall(){
 if(indata!=null){
 try {
 indata.close();
 } catch (ioexception e) {
 // todo auto-generated catch block
 e.printstacktrace();
 }
 indata = null;
 }
 
 if(outdata!=null){
 try {
 outdata.close();
 } catch (ioexception e) {
 // todo auto-generated catch block
 e.printstacktrace();
 }
 outdata = null;
 } 
 
 if(clientmailsocket!=null){
 try {
 clientmailsocket.close();
 } catch (ioexception e) {
 // todo auto-generated catch block
 e.printstacktrace();
 }
 clientmailsocket = null;
 }
 
 }
 
 
 /**
 * 讀取文件內容
 * @param filename
 * @return
 */
 public string readfile(string filename){
 byte[] filebuffer = new byte[1024];
 int realsize = 0;
 stringbuffer readcontent = new stringbuffer();
 try {
 inputstream infile = new fileinputstream(new file(filename));
 while(true){
 realsize = infile.read(filebuffer);
 if(-1==realsize) break;
 readcontent.append(new string(filebuffer,0,realsize));
 }
 } catch (filenotfoundexception e) {
 // todo auto-generated catch block
 e.printstacktrace();
 } catch (ioexception e) {
 // todo auto-generated catch block
 e.printstacktrace();
 }
 return readcontent.tostring();
 }
 /**
 * base64編碼函數
 * 將指定的字符串編碼為base64格式的字符串
 * @param src
 * @return
 */
 public static string base64encode(string src) {
 if (src == null || src.length() == 0)
 return "";
 string encodingtable = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789+/";
 byte[] buffer = src.getbytes();
 int readnow, i, res;
 char[] writebuf = new char[4];
 char[] buf = new char[3];
 string encodedstr = "";
 int readindex = 0;
 int len = buffer.length;
 boolean isend;
 int byteswritten = 0;
 readnow = 0;
 do {
 isend = false;
 for (i = 0; i < 3; i++) {
 if (readindex >= len) {
 isend = true;
 readnow = i;
 break;
 }
 buf[i] = (char) (((byte) buffer[readindex]) & 0x00ff);
 readindex = readindex + 1;
 }
 if (isend)
 break;
 writebuf[0] = encodingtable.charat((buf[0] >> 2) & 0x003f);
 writebuf[1] = encodingtable
 .charat(((buf[0] & 3) << 4 | (buf[1] >> 4)) & 0x003f);
 writebuf[2] = encodingtable
 .charat(((buf[1] & 15) << 2 | (buf[2] >> 6)) & 0x003f);
 writebuf[3] = encodingtable.charat((buf[2] & 63) & 0x003f);
 for (i = 0; i < 4; i++)
 encodedstr = encodedstr + writebuf[i];
 byteswritten = byteswritten + 4;
 if ((byteswritten % 76) == 0) {
 encodedstr = encodedstr + "";
 }
 } while (readnow != 3);
 if (readnow < 3) {
 switch (readnow) {
 case 1:
 writebuf[0] = encodingtable.charat((buf[0] >> 2) & 0x003f);
 writebuf[1] = encodingtable
 .charat(((buf[0] & 3) << 4) & 0x003f);
 writebuf[2] = '=';
 writebuf[3] = '=';
 for (i = 0; i < 4; i++)
 encodedstr = encodedstr + writebuf[i];
 break;
 case 2:
 writebuf[0] = encodingtable.charat((buf[0] >> 2) & 0x003f);
 writebuf[1] = encodingtable
 .charat(((buf[0] & 3) << 4 | (buf[1] >> 4)) & 0x003f);
 writebuf[2] = encodingtable
 .charat(((buf[1] & 15) << 2) & 0x003f);
 writebuf[3] = '=';
 for (i = 0; i < 4; i++)
 encodedstr = encodedstr + writebuf[i];
 break;
 default:
 break;
 }
 }
 return (encodedstr);
 }
}