學(xué)習(xí)javamail
雖然javamail出來很久了,但是一直沒有怎么深入研究,今天學(xué)了一會(huì),寫了個(gè)小程序如下,能發(fā)送郵件:
import java.util.* ;
import java.io.* ;
import javax.mail.* ;
import javax.mail.internet.* ;
import javax.activation.* ;
public class Mail {
//定義發(fā)件人、收件人、主題等
String to="";
String from="";
String host="";
String filename="";
String subject="";
//用于保存發(fā)送附件的文件名的集合
Vector file = new Vector();
//做一個(gè)可以傳發(fā)件人等參數(shù)的構(gòu)造
public Mail (String to,String from,String smtpServer,String subject){
//初始化發(fā)件人、收件人、主題等
this.to=to;
this.from=from;
this.host=smtpServer;
this.subject=subject;
}
//該方法用于收集附件名
public void attachfile(String fname){
file.addElement(fname);
}
//開始發(fā)送信件的方法
public boolean startSend(){
//創(chuàng)建Properties對象
Properties props = System.getProperties();
//創(chuàng)建信件服務(wù)器
props.put("mail.smtp.host", host);
//得到默認(rèn)的對話對象
Session session=Session.getDefaultInstance(props, null); try {
//創(chuàng)建一個(gè)消息,并初始化該消息的各項(xiàng)元素
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
InternetAddress[] address={new InternetAddress(to)};
msg.setRecipients(Message.RecipientType.TO,address);
msg.setSubject(subject);
//后面的BodyPart將加入到此處創(chuàng)建的Multipart中
Multipart mp = new MimeMultipart();
//利用枚舉器方便的遍歷集合
Enumeration efile=file.elements();
//檢查序列中是否還有更多的對象
while(efile.hasMoreElements()){
MimeBodyPart mbp=new MimeBodyPart();
//選擇出每一個(gè)附件名
filename=efile .nextElement().toString();
//得到數(shù)據(jù)源
FileDataSource fds=new FileDataSource(filename);
//得到附件本身并至入BodyPart
mbp.setDataHandler(new DataHandler(fds));
//得到文件名同樣至入BodyPart
mbp.setFileName(fds.getName());
mp.addBodyPart(mbp);
}
//移走集合中的所有元素
file.removeAllElements();
//Multipart加入到信件
msg.setContent(mp);
//設(shè)置信件頭的發(fā)送日期
msg.setSentDate(new Date());
//發(fā)送信件
Transport.send(msg);
} catch (MessagingException mex) {
mex.printStackTrace();
Exception ex = null;
if ((ex=mex.getNextException())!=null){
ex.printStackTrace();
}
return false;
}
return true;
}
public static void main(String args[]){
Mail m1=new Mail("wang@localhost","wang@locahost","localhost","hello");
m1.attachfile("mail.java");
try{
m1.startSend();
}catch(Exception e){
System.out.println("error");}
}
}
要運(yùn)行它得首先有個(gè)自己得郵件服務(wù)器,我用得是從d61上下得破解得一個(gè)郵件服務(wù)器,叫做MDaemon,挺不錯(cuò)得,下一步?jīng)Q定寫一個(gè)收email得程序。