我正在尝试将多个文件附加到电子邮件中。
除了文本文件缺少第一行之外,它工作正常。
注意:为了便于阅读,删除了所有错误处理。此外,假设正确设置了收件人/发件人/主题等(电子邮件发送完美 - 除了附件问题)。
首先,这是我正在使用的代码:
MimeMessage oMessage = new MimeMessage(oSession);
// Create a multipart message
Multipart oMultiPart = new MimeMultipart();
// Create the message part
BodyPart oMessageBodyPart = new MimeBodyPart();
// Set the Message Body
String strFormat = oEmail.getFormat();
String strBody = oEmail.getBody();
oMessageBodyPart.setContent(strBody,strFormat);
oMultiPart.addBodyPart(oMessageBodyPart);
List<String> oAttachmentNames = oEmail.getAttachments();
for (String strAttachmentName : oAttachmentNames)
{
// Parse file from URL
URL oURL = new URL(strAttachmentName);
MimeBodyPart oAttachmentPart = new MimeBodyPart(oURL.openStream());
oAttachmentPart.setFileName(strAttachmentName);
oMultiPart.addBodyPart(oAttachmentPart);
}
// Add all contents (body + attachments)
oMessage.setContent(oMultiPart);
顺便说一下,文本文件如下:
This is the Test file
(intentional line break)
Line 1
Line 2
这是调试输出:
Content-Type: multipart/mixed;
boundary="----=_Part_0_29194312.1354442889470"
------=_Part_0_29194312.1354442889470
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: 7bit
Plain Text Email.
------=_Part_0_29194312.1354442889470
This is the Test file
Content-Disposition: attachment;
filename="http://mysite.com/temp/Test.txt"
Line 1
Line 2
------=_Part_0_29194312.1354442889470--
.
250 OK id=1Tf6T5-0004E9-Nn
QUIT