电子邮件C#的FileStream附件



我写了一个代码来制作电子邮件发送附件,但我不明白如何不仅为txt文件制作附件。我知道所有的二进制文件都被破坏了,因为";File.OpenText";在我的代码中。有人可以向我解释,如何使它适用于所有文件,而不仅仅是txt。

public async Task<ResponseData> SendEmail(VictimData victimData, SmtpData senderData, LetterData letter)
{
ResponseData response = new ResponseData();
BodyBuilder bodyBuilder = new BodyBuilder();
string newAttachment = "";
try
{
MimeMessage message = new MimeMessage();
message.From.Add(new MailboxAddress(senderData.senderName, senderData.senderEmail));
message.To.Add(new MailboxAddress("", victimData.email));
/*message.Bcc.Add(new MailboxAddress(senderData.senderName, senderData.senderEmail));
message.ReplyTo.Add(new MailboxAddress(senderData.senderName, senderData.senderEmail));*/
message.Subject = letter.subject;
if (letter.isHtml)
{
bodyBuilder.HtmlBody = letter.body;
}
else
{
bodyBuilder.TextBody = letter.body;
}
foreach (var attachment in letter.attachment)
{
newAttachment = ReadAndReplaceAttachment(attachment.filePath, victimData.email, attachment.fileName);
bodyBuilder.Attachments.Add(newAttachment);
File.Delete(newAttachment);
Console.WriteLine(newAttachment);
}
message.Body = bodyBuilder.ToMessageBody();
await client.SendAsync(message);

response.status = true;
response.messages = "";
return response;
}
catch (Exception ex)
{
response.messages = ex.Message;
response.status = false;
return response;
}
}
private string ReadAndReplaceAttachment(string filePath, string email, string newFileName)
{
Replacer replacer = new Replacer();
string tempFile = Path.Combine(Helpers.tempPath, replacer.DoReplace(newFileName, email));//Path.GetTempPath() + Guid.NewGuid().ToString() + Path.GetExtension(filePath);
string contentResult = "";
using (StreamReader sr = File.OpenText(filePath))
{
contentResult = sr.ReadToEnd();
contentResult = replacer.DoReplace(contentResult, email);
sr.Close();
}
using (var tw = new StreamWriter(tempFile, true))
{
tw.Write(contentResult);
}
return tempFile;
}

您需要更改代码,以便只为txt文件而不为任何其他类型的文件调用ReadAndReplaceAttachment()方法。对于非文本文件,只需附加attachment.filePath引用的原始文件即可。

相关内容

  • 没有找到相关文章

最新更新