1

我创建了一个像字符串一样的文件内容:

string fileContent = CreateContent();

然后我创建了Attachment

Attachment fileAttachment = null;
var stream = new MemoryStream();
var writer = new StreamWriter(stream);
if (!String.IsNullOrEmpty(fileContent))
{
    writer.Write(fileContent);
    writer.Flush();
    fileAttachment = new Attachment(
        stream,
        attachmentName,
        MediaTypeNames.Text.Plain);
}

之后,我发送了电子邮件:

SendEmail.SendEmailWithFile(strEmailSubject, fromEmail, fileAttachment);

并关闭:

writer.Close();
stream.Close();

看起来一切正常。但事实并非如此。问题是该SendEmailWithFile方法应该发送fileAttachment给 2 个不同的人:

Public Sub SendEmailWithFile(strEmailSubject, fromEmail, fileAttachment)
 Dim emlEmail As Net.Mail.MailMessage = s.GetMailMessage()
 Dim smtp As Net.Mail.SmtpClient = New Net.Mail.SmtpClient
 emlEmail.To.Add(user.EmailAddress)
 ...
 If fileAttachmentIsNot Nothing Then
    emlEmail.Attachments.Add(fileAttachment)
 End If
 smtp.Send(emlEmail)//1

 If Not String.IsNullOrEmpty(configurationManager.AppSettings("additionalEmailTo")) Then
  emlEmail.To.Clear()
  Dim address As String = configurationManager.AppSettings("additionalEmailTo")
  emlEmail.To.Add(address)
  smtp.Send(emlEmail)//2
 End If
End Sub

电子邮件发送没有错误,但第一封电子邮件 (//1) - 包含空文件,第二封电子邮件 (//2) 包含完整文件。

我应该怎么做才能将正确的文件发送到两个电子邮件地址?

4

1 回答 1

1

为什么要发送两次?您可以使用emlEmail.To.Add添加更多收件人,或者如果您不希望他们看到彼此的电子邮件地址,请使用密件抄送类。

Public Sub SendEmailWithFile(strEmailSubject, fromEmail, fileAttachment)
 Dim emlEmail As Net.Mail.MailMessage = s.GetMailMessage()
 Dim smtp As Net.Mail.SmtpClient = New Net.Mail.SmtpClient
 emlEmail.To.Add(user.EmailAddress)
 If Not String.IsNullOrEmpty(configurationManager.AppSettings("additionalEmailTo")) Then
  Dim address As String = configurationManager.AppSettings("additionalEmailTo")
  emlEmail.To.Add(address)
 End If
...
 If fileAttachmentIsNot Nothing Then
    emlEmail.Attachments.Add(fileAttachment)
 End If
 smtp.Send(emlEmail)//1
 End Sub
于 2013-11-13T15:13:09.887 回答