如何使用 java 邮件 api 发送任何类型的附件?
How to send any type of attachment using java mail api?
我可以发送仅附有文本文件的邮件,而且我使用的是文件路径。我想要一个代码使用文件 inputstream
发送任何类型的附件
我可以发送仅附有文本文件的邮件,而且我正在使用文件。
messageBodyPart = new MimeBodyPart();
String filename = "/home/manisha/file.txt";
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
我希望代码使用 java api.
发送任何类型的附件
事实证明,ByteArrayDataSource 可用于发送任何类型的流。除了流之外,您还需要指定 mime 类型,因为没有它就无法知道类型。如果 InputStream 表示 jpeg 图像,您将使用 "image/jpeg" 作为传递给 ByteArrayDataSource 的类型。
知道ByteArrayDataSource会把InputStream完全读入字节数组中进行处理。如果 InputStream 非常大,则可能会消耗大量内存。再一次,大多数电子邮件系统限制附件大小。
请注意,此代码尚未准备好生产,需要错误/异常处理。
messageBodyPart = new MimeBodyPart();
String filename = "/home/manisha/file.txt";
//
// FileInputStream is just for the example. You can use other InputStreams as well.
//
InputStream inputStream = new FileInputStream(filename);
DataSource source;
try (InputStream inputStream = new FileInputStream(filename)) {
source = new ByteArrayDataSource(inputStream, "text/plain;charset=UTF-8");
}
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
// Send the complete message parts
message.setContent(multipart);
[编辑] 下面是一些测试 InputStream 是否有数据的代码。您可以使用上面的源调用它以打印出输入流中的字节数。
private static void printDataSourceByteCount(DataSource source) throws IOException {
try (InputStream is = source.getInputStream()) {
long totalBytesRead = 0;
byte [] buffer = new byte[2048];
int bytesRead = is.read(buffer);
while(bytesRead > 0) {
totalBytesRead += bytesRead;
bytesRead = is.read(buffer);
}
System.out.println(String.format("Read %d bytes", totalBytesRead));
}
}
[编辑] 这是我使用测试 pdf 的功能齐全的示例。只要将 MIME 类型更改为 "text/plain".
,文本文件也能正常工作
public static void main(String[] args) {
// Recipient's email ID needs to be mentioned.
String to = "<to email>";
// Sender's email ID needs to be mentioned
String from = "<from email>";
final String username = "<email server username>";// change accordingly
final String password = "<email server password>";// change accordingly
// Set to your email server
String host = "mail.acme.com";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "false");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", "25");
// Get the Session object.
Session session = Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
// Create a default MimeMessage object.
Message message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the header.
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
// Set Subject: header field
message.setSubject("Testing Subject");
// Create the message part
BodyPart messageBodyPart = new MimeBodyPart();
// Now set the actual message
messageBodyPart.setText("Hello. Attached is a very important PDF.");
// Create a multipar message
Multipart multipart = new MimeMultipart();
// Set text message part
multipart.addBodyPart(messageBodyPart);
// Part two is attachment
messageBodyPart = new MimeBodyPart();
String filename = "/Users/rick/Tmp/test.pdf";
DataSource source;
try (InputStream inputStream = new FileInputStream(filename)) {
source = new ByteArrayDataSource(inputStream, "application/pdf");
}
printDataSourceByteCount(source);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName("SecretsOfTheUniverse.pdf");
multipart.addBodyPart(messageBodyPart);
// Send the complete message parts
message.setContent(multipart);
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
} catch (MessagingException e) {
// TODO handle the error
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO handle the error
e.printStackTrace();
} catch (IOException e) {
// TODO handle the error
e.printStackTrace();
}
}
我可以发送仅附有文本文件的邮件,而且我使用的是文件路径。我想要一个代码使用文件 inputstream
发送任何类型的附件我可以发送仅附有文本文件的邮件,而且我正在使用文件。
messageBodyPart = new MimeBodyPart();
String filename = "/home/manisha/file.txt";
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
我希望代码使用 java api.
发送任何类型的附件事实证明,ByteArrayDataSource 可用于发送任何类型的流。除了流之外,您还需要指定 mime 类型,因为没有它就无法知道类型。如果 InputStream 表示 jpeg 图像,您将使用 "image/jpeg" 作为传递给 ByteArrayDataSource 的类型。
知道ByteArrayDataSource会把InputStream完全读入字节数组中进行处理。如果 InputStream 非常大,则可能会消耗大量内存。再一次,大多数电子邮件系统限制附件大小。
请注意,此代码尚未准备好生产,需要错误/异常处理。
messageBodyPart = new MimeBodyPart();
String filename = "/home/manisha/file.txt";
//
// FileInputStream is just for the example. You can use other InputStreams as well.
//
InputStream inputStream = new FileInputStream(filename);
DataSource source;
try (InputStream inputStream = new FileInputStream(filename)) {
source = new ByteArrayDataSource(inputStream, "text/plain;charset=UTF-8");
}
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
// Send the complete message parts
message.setContent(multipart);
[编辑] 下面是一些测试 InputStream 是否有数据的代码。您可以使用上面的源调用它以打印出输入流中的字节数。
private static void printDataSourceByteCount(DataSource source) throws IOException {
try (InputStream is = source.getInputStream()) {
long totalBytesRead = 0;
byte [] buffer = new byte[2048];
int bytesRead = is.read(buffer);
while(bytesRead > 0) {
totalBytesRead += bytesRead;
bytesRead = is.read(buffer);
}
System.out.println(String.format("Read %d bytes", totalBytesRead));
}
}
[编辑] 这是我使用测试 pdf 的功能齐全的示例。只要将 MIME 类型更改为 "text/plain".
,文本文件也能正常工作public static void main(String[] args) {
// Recipient's email ID needs to be mentioned.
String to = "<to email>";
// Sender's email ID needs to be mentioned
String from = "<from email>";
final String username = "<email server username>";// change accordingly
final String password = "<email server password>";// change accordingly
// Set to your email server
String host = "mail.acme.com";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "false");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", "25");
// Get the Session object.
Session session = Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
// Create a default MimeMessage object.
Message message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the header.
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
// Set Subject: header field
message.setSubject("Testing Subject");
// Create the message part
BodyPart messageBodyPart = new MimeBodyPart();
// Now set the actual message
messageBodyPart.setText("Hello. Attached is a very important PDF.");
// Create a multipar message
Multipart multipart = new MimeMultipart();
// Set text message part
multipart.addBodyPart(messageBodyPart);
// Part two is attachment
messageBodyPart = new MimeBodyPart();
String filename = "/Users/rick/Tmp/test.pdf";
DataSource source;
try (InputStream inputStream = new FileInputStream(filename)) {
source = new ByteArrayDataSource(inputStream, "application/pdf");
}
printDataSourceByteCount(source);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName("SecretsOfTheUniverse.pdf");
multipart.addBodyPart(messageBodyPart);
// Send the complete message parts
message.setContent(multipart);
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
} catch (MessagingException e) {
// TODO handle the error
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO handle the error
e.printStackTrace();
} catch (IOException e) {
// TODO handle the error
e.printStackTrace();
}
}