首页 > 开发 > 综合 > 正文

使用ESMTP(SMTP)进行邮件发送

2020-02-05 14:04:51
字体:
来源:转载
供稿:网友
使用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);
}
}




发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表