1、用JAVA发送含有附件的邮件
public void sendKREmailAndFile(String[] toEmail, String mailSubject, String mailContent,List<File> fileList) throws MessagingException { Properties prop = new Properties(); prop.put("mail.smtp.auth", "true"); prop.put("mail.smtp.host", host); prop.put("mail.smtp.port", port); prop.put("mail.debug", "true"); prop.put("mail.smtp.starttls.enable", "true"); Session session = Session.getInstance(prop, new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(userName, password); } }); MimeMessage message = new MimeMessage(session); message.setSubject(mailSubject); message.setFrom(new InternetAddress(senderEmail)); InternetAddress[] toAddress = new InternetAddress[toEmail.length]; // 设置收件人的邮箱 for (int i = 0; i < toAddress.length; i++) { toAddress[i] = new InternetAddress(toEmail[i]); } message.setRecipients(Message.RecipientType.TO, toAddress); message.setSubject(mailSubject, Charsets.UTF_8.name()); String msg = mailContent; MimeBodyPart mimeBodyPart = new MimeBodyPart(); mimeBodyPart.setContent(msg, messageType); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(mimeBodyPart); //关键代码:发送附件 if(fileList != null){ for(File file : fileList){ MimeBodyPart appendix = new MimeBodyPart(); appendix.setDataHandler(new DataHandler(new FileDataSource(file.getAbsolutePath()))); appendix.setFileName(file.getName()); multipart.addBodyPart(appendix); } } message.setContent(multipart); Transport.send(message); }
2、其实和发送普通邮件的基本差不多。只是加了下面的代码,所以发送不带附件和带附件的邮件,都可以用这个方法
//关键代码:发送附件 if(fileList != null){ for(File file : fileList){ MimeBodyPart appendix = new MimeBodyPart(); appendix.setDataHandler(new DataHandler(new FileDataSource(file.getAbsolutePath()))); appendix.setFileName(file.getName()); multipart.addBodyPart(appendix); } }
标签:JAVA,prop,appendix,file,附件,new,message,MimeBodyPart,邮件 From: https://www.cnblogs.com/wwssgg/p/16998986.html