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
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
I am sending emails thorugh c#. The body of the mail is dynamic i.e. user fills it in before sending the mail. Issue is the body text is coming in a single line instead of multiple lines as they should.
using (MailMessage mm = new MailMessage(txtEmail.Text.Trim(), email.Trim()))
{
try
{
mm.CC.Add(txtcc.Text.Trim());
mm.Subject = txtSubject.Text.Trim();
mm.Body = txtBody.Text;
MemoryStream pdf = new MemoryStream(bytes);
mm.Attachments.Add(new Attachment(pdf, "Report.pdf"));
mm.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
NetworkCredential credentials = new NetworkCredential();
credentials.UserName = txtEmail.Text.Trim();
credentials.Password = txtPassword.Text.Trim();
smtp.UseDefaultCredentials = true;
smtp.Credentials = credentials;
smtp.Port = 587;
smtp.Send(mm);
}
catch (Exception ex)
{
Alert.show1("Could not send the e-mail - error: " + ex.Message, this);
return;
}
}
If you dont need the potential of HTML formatting, you could avoid the problem changing the email format to plain text. This could also avoid user entering text that could be parsed as html.
mm.IsBodyHtml = false;
Otherwise you should change the end line character to html breaking line:
mm.IsBodyHtml = true;
mm.Body = mm.Body.Replace(#"\n", "<br />");
In case of the html format option, It would be wise to follow Fildor's comment and add an alternateView in plain text for email clients that are not html capable.
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 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)