javamail发送附件不通过也不报错

mayanqi mayanqi 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
发送附件的代码如下,使用的是struts,所以附件的上传是使用FormFile(mailForm)
public void sendFile(MailForm mailForm,boolean debug) throws Exception
{
String from = mailForm.getFrom();
String to = mailForm.getTo();
String userName = mailForm.getUserName();
String password = mailForm.getPassword();
FormFile file = mailForm.getFile();
String content = mailForm.getContent();

String mailServer = this.getDomain(from);
Properties props = new Properties();
props.put("mail.smtp.host", mailServer);
props.put("mail.smtp.auth", "true");
props.put("mail.transport.protocol", "smtp");

Session session = Session.getInstance(props);
if(debug)
{
session.setDebug(debug);
}

Message msg = new MimeMessage(session);
BodyPart filePart = new MimeBodyPart();
String fileName = mailForm.getFile().getFileName();
//这个ByteDataSource是自己实现的DataSource
ByteDataSource dataSource = new ByteDataSource(file);
filePart.setDataHandler(new DataHandler(dataSource));
filePart.setFileName(fileName);

Multipart mulPart = new MimeMultipart();
mulPart.addBodyPart(filePart);

filePart = new MimeBodyPart();
filePart.setContent(content, "text/html;charset=gb2312");
mulPart.addBodyPart(filePart);

msg.setContent(mulPart);
msg.setSubject(mailForm.getSubject());
msg.setFrom(new InternetAddress(from));
msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
msg.setSentDate(new Date());
msg.saveChanges();

Transport transport = session.getTransport();
transport.connect(userName, password);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
}
...全文

相关推荐

评论 9
收藏 已收藏
分享
返回顶部
mayanqi
Java SE 62,620 成员 307,251 内容