javamail使用方法

下面是一段用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);
trans.sendMessage(msg, msg.getAllRecipients());
trans.close();

}catch(AuthenticationFailedException e){
map.put("state", "failed");
message="Mail send fail!Error caused:auth error!\n";
e.printStackTrace();
}catch (MessagingException e) {
message="Mail send fail!Error caused:\n"+e.getMessage();
map.put("state", "failed");
e.printStackTrace();
Exception ex = null;
if ((ex = e.getNextException()) != null) {
System.out.println(ex.toString());
ex.printStackTrace();
}
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值