I created C# Console App and I can't send email with file attachment named "testfile" and has no extension.
It successfully sends, but with only the first attachment ("test.png")
How can I send this file?
Here is my code:
internal static void SendTest()
{
MailMessage mail = new MailMessage("Punter#gmail.com", "Michael378#live.com",
"Success", "Attachment email");
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com", 587);
SmtpServer.Credentials = new System.Net.NetworkCredential("Punter#gmail.com", "BrudoTass");
SmtpServer.EnableSsl = true;
string test1 = #"C:\Users\Admin\Desktop\test.png"; //Picture
string test2 = #"C:\Users\Admin\Desktop\testfile"; //File without extension
var attachment1 = new Attachment(test1);
var attachment2 = new Attachment(test2);
mail.Attachments.Add(attachment1);
mail.Attachments.Add(attachment2);
SmtpServer.Send(mail);
}
Try This way
foreach (MessageAttachment ma in msg.Attachments)
mail.Attachments.Add(BuildAttachment(ma));
private Attachment BuildAttachment(MessageAttachment ma)
{
Attachment att = null;
if (ma == null || ma.FileContent == null)
return att;
att = new Attachment(new MemoryStream(ma.FileContent), ma.FileName + ma.FileType, ma.FileType.GetMimeType());
att.ContentDisposition.CreationDate = ma.CreationDate;
att.ContentDisposition.ModificationDate = ma.ModificationDate;
att.ContentDisposition.ReadDate = ma.ReadDate;
att.ContentDisposition.FileName = ma.FileName;
att.ContentDisposition.Size = ma.FileSize;
return att;
}
Related
I can send attachments with URLs, But, looking for support to send a file with an attachment. that too should download from url and attach with mail.
MailMessage mail = new MailMessage();
mail.From = new MailAddress("mymail#email.com");
//to mail address
mail.To.Add(txtEmail.Text);
//Add the Attachment
mail.Attachments.Add(data);
//set the content
mail.Subject = txtSubject.Text;
mail.Body = "Kindly find the below attachments with the link, https://www.python.org/static/img/python-logo#2x.png";
//send the message
SmtpClient smtp = new SmtpClient("*****.********.net");
NetworkCredential Credentials = new NetworkCredential("mymail#email.com", "********");
smtp.Credentials = Credentials;
smtp.Send(mail);
Here I'm sending mail with URL as a file,
But I want to attach a file instead of sending a link
The sample URL was added as an image link.. But I wanted to add a pdf link..
In this case, I want to download a file and attach it with mail,
I use it mostly in my all projects it's working fine. its with base 64
First, make sure your Gmail account is turned on for sending emails.
public static async Task SendEmail(string toUser, string subject, string body
, string username, string password, string port, string smtpServer, string ccUsers = "", string base64Url = "")
{
var toAddress = new System.Net.Mail.MailAddress(toUser, toUser);
System.Net.Mail.MailMessage emessage = new System.Net.Mail.MailMessage();
emessage.To.Add(toAddress);
if (!string.IsNullOrEmpty(ccUsers))
{
string[] ccIds = ccUsers.Split(',');
foreach (string item in ccIds)
{
emessage.CC.Add(new System.Net.Mail.MailAddress(item));
}
}
emessage.Subject = subject;
emessage.From = new System.Net.Mail.MailAddress(username);
emessage.Body = body;
emessage.IsBodyHtml = true;
System.Net.Mail.SmtpClient sc = new System.Net.Mail.SmtpClient();
if (!string.IsNullOrEmpty(base64Url))
{
base64Url = base64Url.Replace("data:image/jpeg;base64,", "");
var imageBytes = Convert.FromBase64String(base64Url);
var stream = new MemoryStream(imageBytes);
System.Net.Mime.ContentType ct = new System.Net.Mime.ContentType(System.Net.Mime.MediaTypeNames.Image.Jpeg);
System.Net.Mail.Attachment at = new System.Net.Mail.Attachment(stream, ct);
at.ContentDisposition.FileName = "Invoice.jpeg";
emessage.Attachments.Add(at);
}
var netCredential = new System.Net.NetworkCredential(username, password);
sc.Host = smtpServer;
sc.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
sc.UseDefaultCredentials = false;
sc.Credentials = netCredential;
sc.EnableSsl = true;
sc.Port = Convert.ToInt32(port);
await sc.SendMailAsync(emessage);
}
It works fine and mail directly reaches inbox instead of spam.. also can able to attach files from serverpath. Thank you everyone who wish to answer my questions..
{
try
{
MailMessage mail = new MailMessage();
mail.From = new MailAddress("mymail#gmail.com");
mail.To.Add("tomail#gmail.com");
//set the content
string filename = "Report1";
string fileurl = Server.MapPath("..");
fileurl = fileurl + #"\mailserver\pdf\generated\" + filename + ".pdf";
//mail.Attachments.Add(new Attachment(fileurl));
if (!string.IsNullOrEmpty(fileurl))
{
Attachment attachment = new Attachment(fileurl, MediaTypeNames.Application.Pdf);
ContentDisposition disposition = attachment.ContentDisposition;
disposition.CreationDate = File.GetCreationTime(fileurl);
disposition.ModificationDate = File.GetLastWriteTime(fileurl);
disposition.ReadDate = File.GetLastAccessTime(fileurl);
disposition.FileName = Path.GetFileName(fileurl);
disposition.Size = new FileInfo(fileurl).Length;
disposition.DispositionType = DispositionTypeNames.Attachment;
mail.Attachments.Add(attachment);
}
mail.Subject = "Subject Text";
mail.Body = "Body Text";
//send the message
SmtpClient smtp = new SmtpClient("smtpout.****.******server.net");
NetworkCredential Credentials = new NetworkCredential("mymail#gmail.com", "Password#123");
smtp.Credentials = Credentials;
//smtp.EnableSsl = true;
smtp.Send(mail);
Response.Write("<center><span style='color:green'><b>Mail has been send successfully!</b></span></center>");
}
catch (Exception ex)
{
//Response.Write("<center><span style='color:red'><b>"+ ex + "</b></span></center>");
Response.Write("<center><span style='color:red'><b>Failed to send a mail...Please check your mail id or Attachment missing</b></span></center>");
}
}
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
This helped to solve this issue.
https://gist.github.com/mvark/8c523eb47670c2fc8da4
Did you try adding sw.Close(); before yiur MailMessage building ?
Below I've added a screenshot of the attachment as it appears in the email.
It opens fine in any PDF reader.
How do I get it to present as an actual PDF? I feel as though I've missed something small...
Here's my code:
public ActionResult SendInvoice(SendInvoiceViewModel model)
{
var Invoice = db.Invoices.FirstOrDefault(x => x.Id == model.Id);
MemoryStream ms = new MemoryStream(Invoice.Document);
Attachment Data = new Attachment(ms, MediaTypeNames.Application.Pdf);
ContentDisposition Disposition = Data.ContentDisposition;
Disposition.CreationDate = Invoice.Date;
Disposition.ModificationDate = Invoice.Date;
Disposition.ReadDate = Invoice.Date;
SendInvoiceMail(model.EmailAddress, Invoice.Number, model.EmailMessage, Data);
}
private void SendInvoiceMail(string emailAddress, string invoiceNumber, string message, Attachment attachment)
{
using (MailMessage Message = new MailMessage())
{
Message.From = new MailAddress("accounts############");
Message.Subject = String.Format("Your store invoice {0}", invoiceNumber);
Message.To.Add(new MailAddress(emailAddress));
Message.Body = message;
Message.Attachments.Add(attachment);
SmtpClient smtp = new SmtpClient("mail.############", 587);
smtp.Credentials = new NetworkCredential("info###########", "##########");
smtp.Send(Message);
};
}
So what did I miss?
Try using the 3-parameter version of the Attachment() constructor. The second parameter lets you give a file name. That file name should end in .pdf.
Try
public ActionResult SendInvoice(SendInvoiceViewModel model)
{
var Invoice = db.Invoices.FirstOrDefault(x => x.Id == model.Id);
MemoryStream ms = new MemoryStream(Invoice.Document);
//Construct a file name for the attachment
var filename = string.Format("{0}.pdf", Invoice.Number);
Attachment Data = new Attachment(ms, filename, MediaTypeNames.Application.Pdf);
ContentDisposition Disposition = Data.ContentDisposition;
Disposition.CreationDate = Invoice.Date;
Disposition.ModificationDate = Invoice.Date;
Disposition.ReadDate = Invoice.Date;
SendInvoiceMail(model.EmailAddress, Invoice.Number, model.EmailMessage, Data);
}
Where you include the file name for the attachment.
I am doing a MVC project, one of the pages, generates a DataTable which dynamically changes. I am supposed to do two functionalities,
1)generate an excel file and make it downloadable for end user - I have a successfully done it.
2) Email the excel attachment to the end user. - I thought it should be a easy one, but it looks complicated. I do not want to save the excel temporarily somewhere in the server, and attach it in email. due to security constraints. (the user will just click on email button and it should reach his email)
Here is my code, It doesnot do anything rather than sending me an empty excel file.
public void EmailCurrMonthSummary()
{
DataAccess da = new DataAccess();
MonthEndSummary mes = new MonthEndSummary();
DataTable tempTable = new DataTable();
mes.MonthEndSummaryTable = da.GetCurrMonthSummary(); //returns a DataTable
MailMessage mail = new MailMessage();
mail.To.Add("User#xxx.com");
mail.From = new MailAddress("Sender#xxx.com");
mail.Body = "Hello World";
mail.Subject = "Month End Status";
System.IO.MemoryStream str = DataToExcel(mes.MonthEndSummaryTable,"MonthEndSummary.xls");
Attachment at = new Attachment(str, "MonthEndSummary.xls");
mail.IsBodyHtml = true;
SmtpClient smtp = new System.Net.Mail.SmtpClient();
smtp.UseDefaultCredentials = true;
smtp.Send(mail);
}
public System.IO.MemoryStream DataToExcel(DataTable dt, string filename)
{
//StreamWriter sw = new StreamWriter();
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
if (dt.Rows.Count > 0)
{
DataGrid dgGrid = new DataGrid();
dgGrid.DataSource = dt;
dgGrid.DataBind();
dgGrid.HeaderStyle.Font.Bold = true;
//Get the HTML for the control.
dgGrid.RenderControl(hw);
//Write the HTML back to the browser.
//Response.ContentType = application/vnd.ms-excel;
Response.ClearContent();
Response.Buffer = true;
Response.ContentType = "application/vnd.ms-excel";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + "");
Response.ContentEncoding = System.Text.Encoding.Default;
}
System.IO.MemoryStream s = new MemoryStream();
System.Text.Encoding Enc = System.Text.Encoding.Default;
byte[] mBArray = Enc.GetBytes(tw.ToString());
s = new MemoryStream(mBArray, false);
//return Content(tw.ToString(), "application/ms-excel");
return s;
}
Can some one help me how to send the excel generated in DataToExcel function ?
After a little tweaking, The below code worked fine for me.
public void EmailCurrMonthSummary()
{
DataAccess da = new DataAccess();
MonthEndSummary mes = new MonthEndSummary();
DataTable tempTable = new DataTable();
mes.MonthEndSummaryTable = da.GetCurrMonthSummary(); //returns a DataTable
MailMessage mail = new MailMessage();
mail.To.Add("User#xxx.com");
mail.From = new MailAddress("Sender#xxx.com");
mail.Body = "Hello World";
mail.Subject = "Month End Status";
System.IO.MemoryStream str = DataToExcel(mes.MonthEndSummaryTable);
Attachment at = new Attachment(str, "MonthEndSummary.xls");
mail.Attachments.Add(at);
mail.IsBodyHtml = true;
SmtpClient smtp = new System.Net.Mail.SmtpClient();
smtp.UseDefaultCredentials = true;
smtp.Send(mail);
}
public System.IO.MemoryStream DataToExcel(DataTable dt)
{
//StreamWriter sw = new StreamWriter();
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
if (dt.Rows.Count > 0)
{
DataGrid dgGrid = new DataGrid();
dgGrid.DataSource = dt;
dgGrid.DataBind();
dgGrid.HeaderStyle.Font.Bold = true;
//Get the HTML for the control.
dgGrid.RenderControl(hw);
//Write the HTML back to the browser.
//Response.ContentType = application/vnd.ms-excel;
Response.ClearContent();
Response.Buffer = true;
Response.ContentType = "application/vnd.ms-excel";
Response.ContentEncoding = System.Text.Encoding.Default;
}
System.IO.MemoryStream s = new MemoryStream();
System.Text.Encoding Enc = System.Text.Encoding.Default;
byte[] mBArray = Enc.GetBytes(tw.ToString());
s = new MemoryStream(mBArray, false);
return s;
}
private static void SetSmtpDetails()
{
ConfigurationModel smtpConfig = GetConfiguration(ConfigurationKey.SMTPServer.ToString());
string smtpServerValue = smtpConfig.Value;
ConfigurationModel smtpUserConfig = GetConfiguration(ConfigurationKey.SMTPUser.ToString());
string smtpUserValue = smtpUserConfig.Value;
ConfigurationModel smtpPasswordConfig = GetConfiguration(ConfigurationKey.SMTPPassword.ToString());
string smtpPAsswordValue = smtpPasswordConfig.Value;
ConfigurationModel smtpSslConfig = GetConfiguration(ConfigurationKey.EnableSsl.ToString());
string smtpEnableSSl = smtpSslConfig.Value;
ConfigurationModel portConfig = GetConfiguration(ConfigurationKey.Port.ToString());
SmtpServer = !string.IsNullOrEmpty(smtpServerValue) ? Convert.ToString(smtpServerValue) : SmtpServer;
SmtpUser = !string.IsNullOrEmpty(smtpUserValue) ? Convert.ToString(smtpUserValue) : SmtpUser;
SmtpPassword = !string.IsNullOrEmpty(smtpPAsswordValue) ? Convert.ToString(smtpPAsswordValue) : SmtpPassword;
EnableSsl = !string.IsNullOrEmpty(smtpEnableSSl) ? Convert.ToBoolean(smtpEnableSSl) : EnableSsl;
Port = Convert.ToInt32(portConfig.Value);
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
}
public static bool SendMail(string fromAddress, string toAddress, string ccAddress, string bccAddress, string subject, string bodyMessage, bool isBodyHtml, string fileName, string fromName)
{
SetSmtpDetails();
if (string.IsNullOrEmpty(fromAddress))
{
fromAddress = SmtpUser;
}
try
{
var mailMessage = new MailMessage();
if (ccAddress != null && ccAddress.Trim().Length > 0)
{
mailMessage.CC.Add(ccAddress);
}
if (bccAddress != null && bccAddress.Trim().Length > 0)
{
mailMessage.Bcc.Add(bccAddress);
}
mailMessage.To.Add(toAddress);
if (fromAddress != null && fromAddress.Trim().Length > 0)
{
if (fromName != null && fromName.Trim().Length > 0)
{
mailMessage.From = new MailAddress(fromAddress, fromName);
}
else
{
mailMessage.From = new MailAddress(fromAddress);
}
}
subject = subject.Replace('\r', ' ').Replace('\n', ' ');
bodyMessage = bodyMessage.Replace("\r\n", "<br />");
mailMessage.BodyEncoding = Encoding.UTF8;
mailMessage.Subject = subject;
mailMessage.Body = bodyMessage;
mailMessage.IsBodyHtml = isBodyHtml;
mailMessage.Priority = MailPriority.High;
if (fileName != null && fileName.Trim().Length > 0 && File.Exists(fileName))
{
mailMessage.Attachments.Add(new Attachment(fileName));
}
var client = new SmtpClient();
try
{
client.Host = SmtpServer;
client.Port = Port;
client.Credentials = new NetworkCredential(fromAddress, SmtpPassword);
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.EnableSsl = EnableSsl;
client.UseDefaultCredentials = true;
ThreadPool.QueueUserWorkItem(o =>
client.SendAsync(mailMessage, Tuple.Create(client, mailMessage)));
}
catch (SmtpException smtpEx)
{
if (smtpEx.Message.Contains("secure connection"))
{
client.EnableSsl = true;
client.Send(mailMessage);
}
return false;
}
}
catch (Exception ex)
{
throw new InvalidOperationException(string.Format("Error occured while sending Email : From Address: {0} \r\n - ToAddress : {1} \r\n ", fromAddress, toAddress), ex);
}
return true;
}
i am sending single mail to more than 1 person. so i am sending mail in for loop with attachement.but while in second loop i am getting file lock error.below is my code.
public string SendMail(string toList, string from, string ccList,
string subject, string body)
{
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
SmtpClient smtpClient = new SmtpClient();
string msg = string.Empty;
try
{
MailAddress fromAddress = new MailAddress(from);
message.From = fromAddress;
message.To.Add(toList);
if (ccList != null && ccList != string.Empty)
message.CC.Add(ccList);
message.Subject = subject;
message.IsBodyHtml = true;
message.Body = body;
// We use gmail as our smtp client
smtpClient.Host = "smtp.gmail.com";
smtpClient.Port = 587;
smtpClient.EnableSsl = true;
smtpClient.UseDefaultCredentials = true;
smtpClient.Credentials = new System.Net.NetworkCredential(TextBox1.Text, TextBox2.Text);
if (FileUpload2.HasFile)
{
// File Upload path
String FileName = FileUpload2.PostedFile.FileName;
FileUpload2.PostedFile.SaveAs(Server.MapPath(FileName));
//Getting Attachment file
Attachment mailAttachment = new Attachment(Server.MapPath(FileName));
//Attaching uploaded file
message.Attachments.Add(mailAttachment);
}
smtpClient.Send(message);
LblMessage.ForeColor = System.Drawing.Color.Green;
LblMessage.Text = "Mail Sent Successfully.";
}
catch (Exception ex)
{
LblMessage.Text = ex.Message;
LblMessage.ForeColor = System.Drawing.Color.Red;
}
return msg;
}
in loop calling this function
for (int i = 0; i < LbEmails.Items.Count; i++)
{
SendMail(LbEmails.Items[i].ToString(), TextBox1.Text, "", TbSubject.Text, TbBody.Text);
}
It looks like you're saving the uploaded file once for each email you send even though it seems to be the same for all the emails. Pull this line out of the SendMail() method and call it before your loop:
FileUpload2.PostedFile.SaveAs(Server.MapPath(FileName));