I am fetch the email with attachment if found attachment then forward that email to some user. I used following code to do so. When I am using below code it sends email with attachment but attachment has no content (blank attachment). can you suggest me where I am wrong?
public bool AddAttachment(System.IO.Stream sm, string fileName)
{
try
{
System.Net.Mail.Attachment atch = new System.Net.Mail.Attachment(sm, fileName);
msg.Attachments.Add(atch);
return true;
}
catch (Exception ex)
{
TraceService(ex.Message + Environment.NewLine + Environment.NewLine + ex.StackTrace);
}
return false;
}
ObjMail.MsgData = strBuilder.ToString();
for (int i = 0; i < sMail.Attachments.Length; i++)
{
if (!string.IsNullOrEmpty(sMail.Attachments[i].Name))
{
if (!sMail.Attachments[i].Name.Contains(".dat"))
{
System.IO.MemoryStream ms = new System.IO.MemoryStream();
System.IO.StreamWriter writer = new System.IO.StreamWriter(ms);
var sr = new StreamReader(ms);
writer.Write(sMail.Attachments[i]);
ObjMail.AddAttachment(ms, sMail.Attachments[i].Name);
}
}
}
ObjMail.SendMail();
To attach use the following code I have used the example to attach a JPG Image
Attachment attach = new Attachment(id + ".jpg");
attach.Name = "WhateverName.jpg";
mail.Attachments.Add(attach);
Try this:
if (!string.IsNullOrEmpty(sMail.Attachments[i].Name))
{
if (!sMail.Attachments[i].Name.Contains(".dat"))
{
System.IO.MemoryStream ms = new System.IO.MemoryStream();
sMail.Attachments[i].ContentStream.CopyTo(ms);
ObjMail.AddAttachment(ms, sMail.Attachments[i].Name);
}
}
Or may be you can use simple:
if (!string.IsNullOrEmpty(sMail.Attachments[i].Name))
{
if (!sMail.Attachments[i].Name.Contains(".dat"))
{
ObjMail.Add(sMail.Attachments[i]);
}
}
ObjMail.SendMail();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.