學習javamail
雖然javamail出來很久了,但是一直沒有怎么深入研究,今天學了一會,寫了個小程序如下,能發送郵件:
import java.util.* ;
import java.io.* ;
import javax.mail.* ;
import javax.mail.internet.* ;
import javax.activation.* ;
public class Mail {
//定義發件人、收件人、主題等
String to="";
String from="";
String host="";
String filename="";
String subject="";
//用于保存發送附件的文件名的集合
Vector file = new Vector();
//做一個可以傳發件人等參數的構造
public Mail (String to,String from,String smtpServer,String subject){
//初始化發件人、收件人、主題等
this.to=to;
this.from=from;
this.host=smtpServer;
this.subject=subject;
}
//該方法用于收集附件名
public void attachfile(String fname){
file.addElement(fname);
}
//開始發送信件的方法
public boolean startSend(){
//創建Properties對象
Properties props = System.getProperties();
//創建信件服務器
props.put("mail.smtp.host", host);
//得到默認的對話對象
Session session=Session.getDefaultInstance(props, null); try {
//創建一個消息,并初始化該消息的各項元素
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將加入到此處創建的Multipart中
Multipart mp = new MimeMultipart();
//利用枚舉器方便的遍歷集合
Enumeration efile=file.elements();
//檢查序列中是否還有更多的對象
while(efile.hasMoreElements()){
MimeBodyPart mbp=new MimeBodyPart();
//選擇出每一個附件名
filename=efile .nextElement().toString();
//得到數據源
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);
//設置信件頭的發送日期
msg.setSentDate(new Date());
//發送信件
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");}
}
}
要運行它得首先有個自己得郵件服務器,我用得是從d61上下得破解得一個郵件服務器,叫做MDaemon,挺不錯得,下一步決定寫一個收email得程序。