我创建了一个类似字符串的文件内容:
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)包含完整文件。
如何将正确的文件发送到这两个电子邮件地址?
答案 0 :(得分:1)
为什么要发送两次?您可以使用emlEmail.To.Add
添加更多收件人,或者如果您不希望他们查看每个人的电子邮件地址,请使用BCC课程。
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