简体   繁体   English

用Java发送电子邮件

[英]Sending Emails in java

I am trying to send email this way but i could not figure out few things 我正在尝试以这种方式发送电子邮件,但我无法弄清楚几件事

  1. How do i use Input Stream object and add as a attachment. 如何使用Input Stream对象并添加为附件。
  2. How to send multiple attachments 如何发送多个附件
  3. How to send Multiple Attachments with HTML body 如何使用HTML正文发送多个附件

I tried below code and i could only send one attachment or HTML body 我尝试使用以下代码,但只能发送一个附件或HTML正文

MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO,
        new InternetAddress(to));

message.addRecipient(Message.RecipientType.CC,
        new InternetAddress(cc));
Address address[] =
        {new InternetAddress(replyTo)};
message.setReplyTo(address);
// Set Subject: header field
message.setSubject(subject);
// Now set the actual message
MimeBodyPart messageBodyPart = new MimeBodyPart();

Multipart multipart = new MimeMultipart();

messageBodyPart = new MimeBodyPart();
String file = "/file.pdf";
String fileName = "attachmentName";

DataSource source = new FileDataSource(file);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(fileName);
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
message.setContent(body, "text/html");
// Send message
Transport.send(message);

This answers 1 question 这回答了1个问题

User ByteArrayDataSource it does have consutructor 用户ByteArrayDataSource它确实具有contrutructor
public ByteArrayDataSource(InputStream is, String type) 公共ByteArrayDataSource(InputStream是,字符串类型)

This answers 2 question of your list. 这回答了您列表中的2个问题。

You can add multiple MimeBodyPart objects to Multipart Object 您可以将多个MimeBodyPart对象添加到Multipart对象

This is code taken from Multipart.java it adds MimeBodyPart objects to vector 这是取自Multipart.java代码,它将MimeBodyPart对象添加到矢量

public synchronized void addBodyPart(BodyPart part) throws MessagingException {
    if (parts == null) {
        parts = new Vector();
        parts.addElement(part);
        part.setParent(this);
    }
}

Every time you call setContent on "message", it overwrites the previous content. 每次在“消息”上调用setContent时,它将覆盖先前的内容。

Have you found the JavaMail FAQ yet? 您找到JavaMail FAQ了吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM