(未知发件人)从java应用程序发送带有在iText中创建的pdf附件的电子邮件时
我在一个网页上有一个链接,它可以从localhost SMTP发送电子邮件,其中包含从iText创建的pdf附件,我在How to create an in-memory PDF report and send as an email attachment using iText and Java之后创建了该附件,并且它可以工作,但是当我收到电子邮件时,我看不到发件人的名称/地址
它在我的gmail收件箱中显示为来自“(未知发件人)”,如果我点击“回复”,则“收件人”框完全为空。在hotmail中显示为来自“(未知)”,但当我打开它时,发件人显示为“admin@whatever.com代表(未知)”
当我通过telnet在服务器上测试SMTP时,我创建的发送方名称就可以通过了。我怎样才能让它在应用程序发送电子邮件时显示出来
以下是发送电子邮件的代码:
String smtpHost = "localhost";
int smtpPort = 25;
String sender = "admin@whatever.com";
String[] recipient = pdfEmail.replaceAll("\\ ", "").split(",");
String content = "whatever";
String subject = "whatever";
Properties props = new Properties();
props.put("mail.smtp.host", smtpHost);
props.put("mail.smtp.user", sender);
props.put("mail.smtp.port", smtpPort);
Session session = Session.getDefaultInstance(props, null);
ByteArrayOutputStream outputStream = null;
try {
//construct the text body part
MimeBodyPart textBodyPart = new MimeBodyPart();
textBodyPart.setText(content);
//now write the PDF content to the output stream
outputStream = new ByteArrayOutputStream();
writePdf(outputStream); //creates PDF
byte[] bytes = outputStream.toByteArray();
//construct the pdf body part
DataSource dataSource = new ByteArrayDataSource(bytes, "application/pdf");
MimeBodyPart pdfBodyPart = new MimeBodyPart();
pdfBodyPart.setDataHandler(new DataHandler(dataSource));
pdfBodyPart.setFileName("test.pdf");
//construct the mime multi part
MimeMultipart mimeMultipart = new MimeMultipart();
mimeMultipart.addBodyPart(textBodyPart);
mimeMultipart.addBodyPart(pdfBodyPart);
//create the sender/recipient addresses
InternetAddress iaSender = new InternetAddress(sender);
InternetAddress[] toAddress = new InternetAddress[recipient.length];
// To get the array of addresses
for( int i=0; i < recipient.length; i++ ) {
toAddress[i] = new InternetAddress(recipient[i]);
}
//construct the mime message
MimeMessage mimeMessage = new MimeMessage(session);
for( int i=0; i < toAddress.length; i++) {
mimeMessage.addRecipient(Message.RecipientType.TO, toAddress[i]);
}
mimeMessage.setSender(iaSender);
mimeMessage.setSubject(subject);
mimeMessage.setRecipients(Message.RecipientType.TO, toAddress);
mimeMessage.setContent(mimeMultipart);
//send off the email
Transport.send(mimeMessage);
} catch(Exception ex) {
ex.printStackTrace();
} finally {
//clean off
if(null != outputStream) {
try { outputStream.close(); outputStream = null; }
catch(Exception ex) { }
}
}
}
# 1 楼答案
试试这个
# 2 楼答案
试着用
mimeMessage.setFrom(...)
代替mimeMessage.setSender(...)