java发送邮件带多个附件_java发送邮件带附件

1 packagecom.smtp;2

3 importjava.util.Date;4 importjava.util.Enumeration;5 importjava.util.Properties;6 importjava.util.Vector;7

8 importjavax.activation.DataHandler;9 importjavax.activation.FileDataSource;10 importjavax.mail.Authenticator;11 importjavax.mail.Message;12 importjavax.mail.MessagingException;13 importjavax.mail.Multipart;14 importjavax.mail.PasswordAuthentication;15 importjavax.mail.Session;16 importjavax.mail.Transport;17 importjavax.mail.internet.InternetAddress;18 importjavax.mail.internet.MimeBodyPart;19 importjavax.mail.internet.MimeMessage;20 importjavax.mail.internet.MimeMultipart;21 importjavax.mail.internet.MimeUtility;22

23 public classSendMail {24

25 publicString toChinese(String text) {26 try{27 text = MimeUtility.encodeText(new String(text.getBytes(), "GB2312"), "GB2312", "B");28 } catch(Exception e) {29 e.printStackTrace();30 }31 returntext;32 }33

34 public booleansendMail(MailBean mb) {35 String host =mb.getHost();36 final String username =mb.getUsername();37 final String password =mb.getPassword();38 String from =mb.getFrom();39 String to =mb.getTo();40 String subject =mb.getSubject();41 String content =mb.getContent();42 String fileName =mb.getFilename();43 Vector file =mb.getFile();44

45 Properties props =System.getProperties();46 props.put("mail.smtp.host", host); //设置SMTP的主机

47 props.put("mail.smtp.auth", "true"); //需要经过验证

48

49 Session session = Session.getInstance(props, newAuthenticator() {50 publicPasswordAuthentication getPasswordAuthentication() {51 return newPasswordAuthentication(username, password);52 }53 });54

55 try{56 MimeMessage msg = newMimeMessage(session);57 msg.setFrom(newInternetAddress(from));58 InternetAddress[] address = { newInternetAddress(to) };59 msg.setRecipients(Message.RecipientType.TO, address);60 msg.setSubject(toChinese(subject));61

62 Multipart mp = newMimeMultipart();63 MimeBodyPart mbpContent = newMimeBodyPart();64 mbpContent.setText(content);65 mp.addBodyPart(mbpContent);66

67 /*往邮件中添加附件*/

68 if (file != null) {69 Enumeration efile =file.elements();70 while(efile.hasMoreElements()) {71 MimeBodyPart mbpFile = newMimeBodyPart();72 fileName =efile.nextElement().toString();73 FileDataSource fds = newFileDataSource(fileName);74 mbpFile.setDataHandler(newDataHandler(fds));75 mbpFile.setFileName(toChinese(fds.getName()));76 mp.addBodyPart(mbpFile);77 }78 System.out.println("添加成功");79 }80

81 msg.setContent(mp);82 msg.setSentDate(newDate());83 Transport.send(msg);84

85 } catch(MessagingException me) {86 me.printStackTrace();87 return false;88 }89 return true;90 }91

92 }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值