日期:2014-05-20  浏览次数:20972 次

如何用java调用默认邮件客户端发送邮件(邮件是带附件的)?
是用java语言调用(vb,vc,delphi的例子网上有很多了)
  实现的效果就像在ie地址栏输入mailto:***@sss.com一样,windows会自动启动默认的邮件客户端(比如OE,foxmail,Lotus Notes等)新建一封邮件,***@sss.com会作为收件人,然后用户点击send就可以发出去了.
  我这个应用不能直接用java调mailto,因为mailto不支持添加附件.也不能用那种需要smtp server参数和用户密码的程序来发送,因为那种程序(比如很多javamail的代码)都是自动发送邮件了.我需要的是会出现邮件客户端的界面,然后需要用户点击send按钮才发送邮件的程序.
  我目前想到了两种方法,哪位大侠提供其中一种方法的源码都可以给分结贴:
  1.用JNI调mapi.
  网上有很多vc,vb的实现都是调用mapi实现的,但是java要调用系统级的api比较麻烦,我所知道的就只有jni了.我对jni也不太懂.如果有高手可以根据网上已有的c++调用邮件客户端的代码,写出jni调用这段代码的java代码,我想这个问题就解决了
  2.调用邮件客户端的api
 我现在电脑上用的是lotus notes,我做的这个软件产品的客户也是用lotus notes作为缺省的邮件客户端.所以如果有人可以用louts notes的api(我大概知道有个notes.jar)来实现也是可以的


------解决方案--------------------
下面是一段用Java mail API发带附件邮件的方法,附件是读的硬盘上的文件,你参考下吧
String message="Mail send OK!";
Session session=null;
Properties props = System.getProperties();
props.put("mail.smtp.host", smtpServer);
if(ifAuth){ //the mail server ask auth
props.put("mail.smtp.auth","true");
MailAuth smtpAuth=new MailAuth(username,password);
session=Session.getDefaultInstance(props, smtpAuth);
}else{
props.put("mail.smtp.auth","false");
session=Session.getDefaultInstance(props, null);
}
session.setDebug(isDebug);

Transport trans = null;
try {
Message msg = new MimeMessage(session);
try{
Address from_address;
if (displayName == null)
from_address = new InternetAddress(from);
else 
from_address = new InternetAddress(from, displayName);
msg.setFrom(from_address);
}catch(java.io.UnsupportedEncodingException e){
e.printStackTrace();
}
//InternetAddress[] address={new InternetAddress(to)};
InternetAddress[] address= InternetAddress.parse(to);
msg.setRecipients(Message.RecipientType.TO,address);
msg.setSubject(subject);

if (cc != null) {
InternetAddress[] ccAddr= InternetAddress.parse(cc);
msg.setRecipients(Message.RecipientType.CC, ccAddr);
}


Multipart mp = new MimeMultipart();
MimeBodyPart mbp = new MimeBodyPart();
//mbp.setContent(content.toString(), "text/html"); //;charset=gb2312");
mbp.setContent(content.toString(), "text/plain"); //;charset=gb2312");
mp.addBodyPart(mbp);
if(!file.isEmpty()){//have attachment
Enumeration efile=file.elements();
while(efile.hasMoreElements()){
mbp=new MimeBodyPart();
filename=efile.nextElement().toString(); //get each attachment name
FileDataSource fds=new FileDataSource(filename); //get the file data source
mbp.setDataHandler(new DataHandler(fds)); //get the attachment content
mbp.setFileName(fds.getName()); //get the file name and include to content
mp.addBodyPart(mbp);
}
file.removeAllElements();
}
msg.setContent(mp); // add the Multipart into mail
msg.setSentDate(new Date()); //set the date in mail header

// send
msg.saveChanges();
trans = session.getTransport("smtp");
trans.connect(smtpServer, username, password);