I trying to send email with attachment using ASP .Net Core 3.1 and C#. Initially the data's are loaded from database and attaching it to Mail-Message as a Memory Stream , I could able to receive the mail but the content inside attachment is always blank.
i tried text format , CSV format , PDF and every attachment i receive along the mail is blank , dont know what i am doing wrong , below is the code,
public void SendEmail(DataTable table)
{
MemoryStream _oMemStream = new MemoryStream();
StreamWriter sw = new StreamWriter(_oMemStream);
foreach (DataColumn column in table.Columns)
{
sw.Write(column.ColumnName.ToString() + ",");
}
foreach (DataRow row in table.Rows)
{
for (int i = 0; i < row.ItemArray.Length; i++)
{
string rowText = row.ItemArray[i].ToString();
sw.Write(rowText + ",");
}
sw.WriteLine();
}
EmailDetailsModel emDetails = new EmailDetailsModel();
emDetails.Body = "Body Of the Mail For Email Functionality";
emDetails.Email = "xxxx";
emDetails.To = "xxx";
emDetails.Subject = "Testing Email Functionality";
emDetails.Password = "xxx";
using (MailMessage mm = new MailMessage(emDetails.Email, emDetails.To))
{
_oMemStream.Position = 0;
mm.Subject = emDetails.Subject;
mm.Body = emDetails.Body;
var contentType = new System.Net.Mime.ContentType(System.Net.Mime.MediaTypeNames.Application.Pdf);
var reportAttachment = new Attachment(_oMemStream, contentType);
reportAttachment.ContentDisposition.FileName = "yourFileName.pdf";
mm.Attachments.Add(reportAttachment);
mm.IsBodyHtml = false;
using (SmtpClient smtp = new SmtpClient())
{
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
NetworkCredential NetworkCred = new NetworkCredential(emDetails.Email, emDetails.Password);
smtp.UseDefaultCredentials = true;
smtp.Credentials = NetworkCred;
smtp.Port = xx;
smtp.Send(mm);
ViewBag.Message = "Email sent.";
}
}
}
Thank you for the suggestion