在使用JavaMail发送邮件一文中,记录了使用JavaMail发送普通文本给多个链接人。这里记录如何使用JavaMail发送带附件的邮件,只是在SendMail类中添加一个新的方法:
public void sendMail(List<String> recipients, String subject, String sendContent, List<String> filePaths)
recipients
表示联系人列表,subject
代表邮件主题,sendContent
代表发送的邮件正文,filePaths
代表添加为邮件附件的文件地址列表,
其代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| public void sendMail(List<String> recipients, String subject, String sendContent, List<String> filePaths) { try { MimeMessage mimeMessage = new MimeMessage(session); mimeMessage.setFrom(new InternetAddress(authenticator.getUsername())); mimeMessage.setSubject(subject); mimeMessage.setSentDate(new Date()); final int num = recipients.size(); InternetAddress[] addresses = new InternetAddress[num]; for (int i = 0; i < num; i++) { addresses[i] = new InternetAddress(recipients.get(i)); } mimeMessage.setRecipients(RecipientType.TO, addresses); MimeMultipart mimeMultipart = new MimeMultipart(); MimeBodyPart mimeBodyPart = new MimeBodyPart(); mimeBodyPart.setContent(sendContent, "text/html;charset=utf-8"); mimeMultipart.addBodyPart(mimeBodyPart); for (String filePath : filePaths) { MimeBodyPart fileBodyPart = new MimeBodyPart(); FileDataSource fds = new FileDataSource(filePath); fileBodyPart.setDataHandler(new DataHandler(fds)); String fileName = MimeUtility.encodeText(fds.getName()); fileBodyPart.setFileName(fileName); mimeMultipart.addBodyPart(fileBodyPart); } mimeMessage.setContent(mimeMultipart); Transport.send(mimeMessage); } catch (MessagingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
|
如上代码所示,发送带附件的邮件内容需要一个MimeMultipart
对象作为容器,为每个附件或邮件正文创建一个MimeBodyPart
对象,并将其添加到容器中。最后,将该容器分配到MimeMessage
的发送内容中。代码24行使用encodeText
方法是为了避免中文乱码的情况。