参考网上的资料:http://www.wangchao.org/bbsdetail_16955.html
这段代码不完整,但是网上99%的javamail发送邮件的例子都是这段代码,说明这是一段经典的代码。
于是操起eclipse来运行这段代码。
由于本人对java不是太熟悉,只是对C了解一些。所以要想修改好这段代码还是有些难度,一开始就想到网上问问,不好意思问,因为网上这么多代码你都看不懂,还要问。于是自己学习起java来,并研读了javamail的api和demo例子,修改好了这段代码,欢迎大家使用。
同时也记录一下方便使用
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
//import javax.activation.*;
//import javax.activation.DataHandler;
public class MailSender{
String ms_strFrom;
String[] ms_astrTo;
//String ms_strSMTPHost;
MimeMessage ms_msg=null;
StringBuffer ms_strbufMsg=null;
// DataHandler eh=null;
public MailSender(
String strFrom,
String[] astrTo,
String[] astrBCC,
String strSubject,
boolean debugging)
{
// String ms_strFrom = strFrom;
// String[] ms_astrTo = astrTo;
boolean ms_debugging = debugging;
Properties props = new Properties();
//props.put("mail.smtp.host",ms_strSMTPHost);
props.put("mail.smtp.host","10.101.2.240");
Session session = Session.getDefaultInstance(props,null);
session.setDebug(ms_debugging);
try{
ms_msg=new MimeMessage(session);
InternetAddress from=new InternetAddress(strFrom);
ms_msg.setFrom(from);
//InternetAddress[] address=new InternetAddress(astrTo[i]);
InternetAddress[] address=new InternetAddress[astrTo.length];
for (int i=0;i<astrTo.length;++i)
{
address[i]=new InternetAddress(astrTo[i]);
}
ms_msg.setRecipients(Message.RecipientType.TO,address);
if (astrBCC != null)
{
address=new InternetAddress[astrBCC.length];
for (int i=0;i<astrBCC.length;++i)
{
// eh.dbg("astrBCC[" +i+ "] is:'" +astrBCC[i]+ "'");
System.out.println("astrBCC[" +i+ "] is:'" +astrBCC[i]+ "'");
address[i]=new InternetAddress(astrBCC[i]);
}
ms_msg.setRecipients(Message.RecipientType.BCC,address);
}
ms_msg.setSubject(strSubject);
ms_strbufMsg=new StringBuffer();
} catch (MessagingException mex){
mex.printStackTrace(System.err);
} catch (Exception ex){
ex.printStackTrace(System.err);
}
}
public void ms_add(String strText)
{
ms_strbufMsg.append(strText);
}
public void ms_send()
{
try {
ms_msg.setContent(new String(ms_strbufMsg),"text/plain");
ms_msg.setText(new String(ms_strbufMsg),"gbk");
Transport.send(ms_msg);
} catch (Exception ex) {
System.out.println("Caught exception in MailSender.ms_send" + ex);
}
}
public static void main(String args[]){
for (int i=0;i<3;i++){
MailSender ms=new MailSender("xxx@xxx.xxx",new String[]{"xxx@xxx.xxx"},new String[]{"xxx@xxx.xxx"},"TEST",true);
ms.ms_add("TESTTESTTESTTESTTE/n,/n这是一封测试邮件!!!" );
// ms.ms_add("这是一封测试邮件!!!" );
ms.ms_send();}
}
}
其中我总结了一下:凡事不要轻易问人,独立思考是基本素质,有些问题时是很简单的,万丈高楼平地起,基础是很重要的,我看到论坛里有些人问的问题是书里都有的东西,拿到论坛来问肯定没人愿意回答,java语言其实是很容易的语言,至少比C简单,所以大家学习起来不难,因为大学里面基本都学过C。