I am able to send an attachment in a mail but the attachment content is blank and size is being shown as 0 bytes.
After doing some search over the internet found that we need to reset the memory stream position to 0 in order to start from start.
I tried that as well but it seems it is not working. Can you please help?
Please find below my code snippet:
NOTE: I am able to save the workbook and Data is present in the saved workbook.
MemoryStream memoryStream = new MemoryStream();
StreamWriter writer = new StreamWriter(memoryStream);
writer.Write(xlWorkbook);
writer.Flush();
memoryStream.Position = 0;
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtpclient");
mail.From = new MailAddress("from#gmail.com");
mail.To.Add("To#gmail.com");
mail.Subject = "Entry";
mail.Body = "Hello, PFA ";
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment(memoryStream,"xls");
attachment.ContentDisposition.FileName = "Input" + DateTime.Now.ToString("yyyyMMdd_hhss") + ".xls";
mail.Attachments.Add(attachment);
SmtpServer.Port = 465;
SmtpServer.UseDefaultCredentials = false;
SmtpServer.Credentials = new System.Net.NetworkCredential("Username", "password");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
writer.Dispose();
I think the attachment is confusing the mail system. Microsoft's recommendation is to specify the content type as an octet. Below is a replacement for initializing the attachment. The reset of your code looks fine.
string filename = "Input" + DateTime.Now.ToString("yyyyMMdd_hhss") + ".xls";
attachment = new System.Net.Mail.Attachment(memoryStream, filename, MediaTypeNames.Application.Octet);
Related
I am creating a pdf using itextsharp. The pdf created normally and post it to the browser so the user can easily save the file to his computer . Now i want this generated pdf automatically send it also with email . I have try to convert the doc before post it to context and attach it to an email but with no any success. My code is:
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = "application/pdf";
HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=mypdf.pdf");
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter stringWriter = new StringWriter();
HtmlTextWriter htmlTextWriter = new HtmlTextWriter(stringWriter);
string imagepath = Server.MapPath(".") + "/assets/myimages/myimage.png";
Document Doc = new Document(PageSize.A4, 10f, 10f, 10f, 10f);
HTMLWorker htmlparser = new HTMLWorker(Doc);
PdfWriter pdfwriter= PdfWriter.GetInstance(Doc, HttpContext.Current.Response.OutputStream);
Doc.Open();
iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(imagepath);
image.ScalePercent(106f,90f);
Doc.Add(image);
//adding elements using itextshart pdf
AddPDf(pdfwriter,Doc);
//to add html in pdf
// htmlparser.Parse(stringReader);
OnEndPage(pdfwriter, Doc);
Doc.Close();
email_send(Doc.ToString());
HttpContext.Current.Response.End();
public void email_send( string filename)
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("myemail#gmail.com");
mail.To.Add("reciever#gmail.com");
mail.Subject = "Test Mail - 1";
mail.Body = "mail with attachment";
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment((Server.MapPath(filename.ToString())));
mail.Attachments.Add(attachment);
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("myemail#gmail.com", "mypass");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
}
The error i get is :
Could not find file
{"Could not find file 'C:\\Admin\\iTextSharp.text.Document'.":"C: \\Admin\\iTextSharp.text.Document"}
The reason for the error is that you're passing the Doc object reference to your email_send method, instead of the file path.
I made a somewhat similar emailing solution by reading the document to a MemoryStream and passing that as the attachment.
public void email_send(Document d)
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("myemail#gmail.com");
mail.To.Add("reciever#gmail.com");
mail.Subject = "Test Mail - 1";
mail.Body = "mail with attachment";
System.IO.MemoryStream ms = new System.IO.MemoryStream();
iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(d, ms);
System.Net.Mime.ContentType ct = new System.Net.Mime.ContentType(System.Net.Mime.MediaTypeNames.Application.Pdf);
Attachment attach = new Attachment(ms, ct);
mail.Attachments.Add(attach);
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("myemail#gmail.com", "mypass");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
writer.Flush();
writer.Dispose();
ms.Dispose();
}
Call it email_send(Doc).
I have a PDF being generated by PDFTK (PDFToolkit). I am trying to add the ReturnedPDF which gets saved to the downloads folder to a MailMessage in C#.
The PDF downloads with no problem; however, attaching isn't going so well.
var pdfContents = PDFHelper.GeneratePDF(pdfPath, formFieldMap);
var newpdffer = PDFHelper.ReturnPDF(pdfContents, "100-" + genUUID.Text + ".pdf");
Returns my PDF filled in just fine (as a downloaded file)... however, I can't seem to figure out how to attach it in MemoryStream. I am simply trying to attach it and email it.
I receive the email - but I get an attachment with nothing in it. SEE MY CODE BELOW:
var doc = new Document();
MemoryStream memoryStream = new MemoryStream();
PdfWriter writer = PdfWriter.GetInstance(doc, memoryStream);
doc.Open();
//doc.Add(new Attachment(thispdfnew));
//doc.Add(new Paragraph("Second Paragraph"));
writer.CloseStream = false;
doc.Close();
memoryStream.Position = 0;
string toemailaddress = email.Text;
string youremailadd = youremail.Text;
MailMessage mm = new MailMessage();
mm.To.Add(new MailAddress(youremail.Text));
MailAddress addressBCC = new MailAddress(email.Text);
mm.Bcc.Add(addressBCC);
mm.Subject = "New form Completed "+Preparedby.Text;
mm.Body = "To view the message, please use an HTML compatible email viewer!";
mm.Attachments.Add(new Attachment(memoryStream, "100-" + genUUID.Text + ".pdf"));
SmtpClient client = new SmtpClient();
client.Port = 587;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential("postmaster#this.com", "343543");
client.Host = "smtp.mailchimp.org";
client.Send(mm);
I've spent the last day googling and trying to figure out how to get the generated PDF into the Mailstream message but can't seem to figure it out. I am using PDFTK which uses iTextSharp to parse the PDF.
I need to send email message with attachment. I'm using below code:
MailMessage msg = new MailMessage("adrFrom", "adrTo", "header", "body");
SmtpClient client = new SmtpClient("hostName", 25);
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential("accountName", "password");
Attachment atch = new Attachment(filePath, MediaTypeNames.Application.Octet);
atch.Name = "FileName.docx";
msg.Attachments.Add(atch);
client.Send(msg);
Message is received, and attachment is there too, but file name looks like ' =?utf-8?B?dXRHRDBZTFJnOUdBMFlzZzBKelF1TkNoPz0NCiA9P3V0Zi04P0I/TG1S?=\', also there is no extension(.docx) and file content looks like it's in the Base64 encoding.
How can I send e-mail message with .docx file saving it extension and name?
Add Contentype to your Attachment
System.Net.Mime.ContentType contentType = new System.Net.Mime.ContentType();
contentType.MediaType = System.Net.Mime.MediaTypeNames.Application.Octet;
contentType.Name = "test.docx";
msg.Attachments.Add(new Attachment("I:/files/test.docx"), contentType);
I have found a solution
The problem was in Russian letters in the file name. Without it everything works fine.
I have a Problem i know how to send email with attachment but i want to learn that if i dont have screenshot.png then i want to send it without attachment my code is below
string email = "hammadptc93#gmail.com";
string pass = "mypassword";
NetworkCredential loginInfo = new NetworkCredential(email, pass);
MailMessage msg = new MailMessage();
SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 587);
msg.From = new MailAddress(email);
msg.To.Add(new MailAddress("hammadptc93#gmail.com"));
msg.Body = value;
msg.Subject = Environment.UserName +" " +
Environment.UserDomainName +" "+ Environment.SystemDirectory ;
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment("screenshot.png");
msg.Attachments.Add(attachment);
smtpClient.EnableSsl = true;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = loginInfo;
smtpClient.SendAsync(msg, "hammad");
Simply checking whether file is present or not will be enough.
if(File.Exists("screenshot.png"))
{
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment("screenshot.png");
msg.Attachments.Add(attachment);
}
Use File.Exists method to check whether you have the attachment. If File.Exists returns false, side step from following lines (wrap them in a if statement)
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment("screenshot.png");
msg.Attachments.Add(attachment);
Hope this helps
I have one form through which ,Sender text his email-id and password and selects attachment
using fileupload,recipients's email id i am getting from database table,email is reaching to recipients fine..but
problem is that when i attach a attachment ,attachment's size goes 0 except 1st email-id
,which i am getting from table....i have pasted code..
foreach (string email_to in list_emails)
{
MailMessage mail = new MailMessage();
mail.To.Add(email_to);
mail.Subject = "UPDATES FROM ATTENDANCE S/W";
mail.From = new MailAddress(txtFrom.Text.ToString());
mail.Body = txtMessage.Text;
if (FileUpload1.HasFile)
{
string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
Attachment myAttachment =
new Attachment(FileUpload1.FileContent, fileName);
mail.Attachments.Add(myAttachment);
}
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.UseDefaultCredentials = false;
smtp.Credentials = new System.Net.NetworkCredential(txtFrom.Text.ToString(), txtPasswd.Text.ToString());
smtp.EnableSsl = true;
smtp.Send(mail);
}
This is happening because FileContent is a Stream and so when you read from it the position of that Stream is left at the end. Consider something like this. At the top of the loop store the bytes, you don't need to keep reading them from the Stream anyway:
bool hasFile = FileUpload1.HasFile;
int fileLen = FileUpload1.PostedFile.ContentLength;
Stream stream = FileUpload1.FileContent;
byte[] file = new byte[fileLen];
stream.Read(file, 0, fileLen);
and then down in the loop, leverage the variable:
new Attachment(new MemoryStream(file) ...
and you'll want to change the if statement to leverage the bool:
if (hasFile)