之前一直在做本地郵件服務器發送,可是沒有成功,都說什么反解析失敗什么的原因,具體的也不太清楚,
最近又學習了用java做郵件發送服務器,還真的成功了分享給大家(以下發送只包括文字內容,不包括附加及圖片,如有不明白的可以聯系我)
java運行:main運行測試的話,包需要java2E1.4
javaweb運行:包需要javaEE5
運行調用SendMailGUI中方法run("發送方地址(隨便起名,但要符合郵件樣式@.)","接收方地址","發送主題","發送內容")
類:SendMailGUI
packageaction;
importjava.util.Arrays;
importjava.util.Hashtable;
importjavax.naming.Context;
importjavax.naming.directory.DirContext;
importjavax.naming.directory.InitialDirContext;
importjavax.naming.directory.Attributes;
importjavax.naming.NamingEnumeration;
importjavax.naming.directory.Attribute;
importjava.io.ByteArrayOutputStream;
importjava.io.FileInputStream;
importjava.io.IOException;
importjava.util.Properties;
importjavax.mail.Session;
importjavax.mail.internet.MimeMessage;
importjavax.mail.internet.InternetAddress;
importjavax.mail.Message;
importjavax.mail.internet.MimeMultipart;
importjavax.mail.BodyPart;
importjavax.mail.internet.MimeBodyPart;
importjavax.activation.FileDataSource;
importjavax.activation.DataHandler;
importjavax.mail.internet.MimeUtility;
importjavax.mail.Multipart;
importjava.util.Date;
importjavax.mail.Transport;
publicclassSendMailGUI{
/**serialVersionUID*/
StringimagePath=null;
javax.swing.JProgressBarbar=newjavax.swing.JProgressBar();
publicintrun(Stringfrom,Stringto,Stringtitle,Stringcontent){
MailMessagemesg=newMailMessage(from,to,title,content);
try
{
sendMail(mesg);
return1;
}catch(Exceptionex){
return0;
}
}
privatevoidsendMail(MailMessagemesg)throwsException
{
//DNS服務器
Stringdns="dns://";
//得到接受方的服務器域名
Stringdomain=mesg.getTo().substring(mesg.getTo().indexOf('@')+1);
Hashtableenv=newHashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.dns.DnsContextFactory");
env.put(Context.PROVIDER_URL,dns);
DirContextctx=newInitialDirContext(env);
Attributesattrs=ctx.getAttributes(domain,newString[]{"MX"});
if(attrs==null||attrs.size()<=0){
thrownewjava.lang.IllegalStateException("錯誤:你的DNS服務器沒有相應的MX記錄!");
}
NamingEnumerationservers=attrs.getAll();
//列出所有郵件服務器:
StringsmtpHost=null;
booleanisSend=false;
St