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.
Related
I am trying to send email with attached pdf, my pdf is in byte array. and when i try to send mail (without pdf) it shows
Message = The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn more at
my code is `string senderEmail = System.Configuration.ConfigurationManager.AppSettings["SenderEmail"].ToString();
string senderPassword = System.Configuration.ConfigurationManager.AppSettings["SenderPassword"].ToString();
SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
client.EnableSsl = true;
client.Timeout = 100000;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential(senderEmail, senderPassword);
MailMessage mailMassege = new MailMessage(senderEmail, toEmail, subject, body);
mailMassege.IsBodyHtml = true;
mailMassege.BodyEncoding = Encoding.UTF8;
client.Send(mailMassege);`
and my pdf is in byte array
byte[] applicationPDFData = actionResult.BuildPdf(ControllerContext);
System.IO.File.WriteAllBytes(filePath + "/hello.pdf", applicationPDFData);
I want to to send mail with this pdf.
thanks in advance
You have to create an attachment and append it to the mail Attachemnts list.
here is an example:
byte[] applicationPDFData = actionResult.BuildPdf(ControllerContext);
Attachment attPDF = new Attachment(new MemoryStream(applicationPDFData), name);
EmailMessage emailMessage = new EmailMessage();
emailMessage.To.Add( new EmailRecipient( toEmail ) );
emailMessage.Subject = subject;
emailMessage.Body = body;
emailMessage.Attachments.Add( attPDF );
regrads
gy
The richtextbox gets it's value copied from a word file that has an image and text. The code below only sends the text and not the image. How can I get it to send both?
using (MailMessage mm = new MailMessage("xxx#gmail.com","xxxx#gmail.com"))
{
mm.Subject = "demo";
TextRange txc = new TextRange(txt_1.Document.ContentStart, txt_1.Document.ContentEnd);
MemoryStream ms = new MemoryStream();
txc.Save(ms, DataFormats.Xaml);
string xamlText = ASCIIEncoding.Default.GetString(ms.ToArray());
// string sa = ASCIIEncoding.Default.GetBytes(ms.ToArray()).ToString();
mm.Body = xamlText;
mm.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
NetworkCredential NetworkCred = new NetworkCredential("xxxx#gmail.com", "xxxxxx");
smtp.UseDefaultCredentials = true;
smtp.Credentials = NetworkCred;
smtp.Port = 587;
smtp.Send(mm);
// ClientScript.RegisterStartupScript(GetType(), "alert", "alert('Email sent.');", true);
}
The problem is that you're taking binary data and explicitly converting it to ASCII text:
string xamlText = ASCIIEncoding.Default.GetString(ms.ToArray());
In so doing, you're altering the original values of the bytes in the image.
You're either going to want to change the BodyEncoding/TransferEncoding of the message Body and encode the data likewise (e.g. Base64 or MIME encoding), or extract the images from the file stream and add them to the mail as attachments. There's a good primer on email encoding here: http://email.about.com/cs/standards/a/mime.htm
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);
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)
I'm using the following code from this answer Sending email in .NET through Gmail. The trouble I'm having is adding an attachment to the email. How would I add an attachment using the code below?
using System.Net.Mail;
var fromAddress = new MailAddress("from#gmail.com", "From Name");
var toAddress = new MailAddress("to#example.com", "To Name");
const string fromPassword = "fromPassword";
const string subject = "Subject";
const string body = "Body";
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
};
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body
})
{
smtp.Send(message);
}
The message object created from your new MailMessage method call has a property .Attachments.
For example:
message.Attachments.Add(new Attachment(PathToAttachment));
Using the Attachment class as proposed in the MSDN:
// Create the file attachment for this e-mail message.
Attachment data = new Attachment(file, MediaTypeNames.Application.Octet);
// Add time stamp information for the file.
ContentDisposition disposition = data.ContentDisposition;
disposition.CreationDate = System.IO.File.GetCreationTime(file);
disposition.ModificationDate = System.IO.File.GetLastWriteTime(file);
disposition.ReadDate = System.IO.File.GetLastAccessTime(file);
// Add the file attachment to this e-mail message.
message.Attachments.Add(data);
Correct your code like this
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment("your attachment file");
mail.Attachments.Add(attachment);
http://csharp.net-informations.com/communications/csharp-email-attachment.htm
hope this will help you.
ricky
Hint: mail body is overwritten by attachment file path if attachment is added after, so attach first and add body later
mail.Attachments.Add(new Attachment(file));
mail.Body = "body";
A one line answer:
mail.Attachments.Add(new System.Net.Mail.Attachment("pathToAttachment"));