problem with send mail method - c#

In this method i send mail
var mail = new MailMessage();
mail.Subject = subject;
mail.SubjectEncoding = Encoding.UTF8;
mail.IsBodyHtml = mailServer.EsHtml;
mail.From = new MailAddress(mailFrom, nomFrom,Encoding.UTF8);
foreach(var item in mailTo)
mail.To.Add(new MailAddress(item.Key, item.Value, Encoding.UTF8));
foreach(var item in mailCC)
mail.Bcc.Add(new MailAddress(item.Key, item.Value, Encoding.UTF8));
mail.Body = message;
mail.BodyEncoding = Encoding.Unicode;
mail.Attachments.Add(new Attachment(attachments));
var clientMail = new SmtpClient();
clientMail.Credentials = new System.Net.NetworkCredential(mailFrom, passMail);
if(mailServer.PuertoCorreo.HasValue)
clientMail.Port = mailServer.PuertoCorreo.Value;
clientMail.Host = mailServer.ServidorCorreo;
clientMail.EnableSsl = mailServer.HabilitarSSL;
clientMail.Send(mail);
And it works fine but in gmail in the body i got this text਍猀搀搀昀ഀ more text and hotmail in attach name i got this 牰敵慢瀮晤.What is wrong in the method?

Try this:
mail.BodyEncoding = System.Text.Encoding.UTF8;

Related

Adding attachments using url in mail with C sharp

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>");
}
}

c# MailMessage From email address display name is not working

I tried to send an email and set display name of the from Email address. But when i received email in my client for instance gmail. Instead of display name i see email address without domain means From Email "FromEmail#abc.com" then when i received it shows me i received email from "FromEmail".
Here is my code
MailMessage mail = new MailMessage();
mail.BodyEncoding = System.Text.Encoding.UTF8;
mail.HeadersEncoding = System.Text.Encoding.UTF8;
mail.SubjectEncoding = System.Text.Encoding.UTF8;
mail.Priority = System.Net.Mail.MailPriority.High;
mail.IsBodyHtml = true;
mail.From = new MailAddress("FromEmail#abc.com","Automate");
mail.To.Add(new MailAddress("ToEmail#abc.com"));
mail.Subject = "This is test email";
mail.Body = "This is test mail.";
SmtpClient client = new SmtpClient("smtp.office365.com");
client.EnableSsl = true;
client.Credentials = new System.Net.NetworkCredential("senderEmail#abc.com", "*****");
client.Send(mail);

ASPX email HTML format

I have this aspx function which send email. Unfortunetely, it does not render html tag on gmail or outlook, but on my android phone looks fine. How to fix it? thanks.
protected void SendMail()
{
var fromAddress = "device#email.com";
var toAddress = "toEMAIL#gmail.com";
const string fromPassword = "****";
var subject = "subject";
string body = " <!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\">";
body += "<HTML><HEAD><META http-equiv=Content-Type content=\"text/html; charset=utf-8\">";
body += "</HEAD><BODY>";
body += "<b>some text some text</b><br></br>";
body += "</BODY></HTML>";
var smtp = new System.Net.Mail.SmtpClient();
{
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.EnableSsl = true;
smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtp.Credentials = new NetworkCredential(fromAddress, fromPassword);
smtp.Timeout = 20000;
}
smtp.Send(fromAddress, toAddress, subject, body);
}
EDITED:
So here is what i have now. But the compiler gives this error:
Line 392: mail.From = fromAddress;
Compiler Error Message: CS0029: Cannot implicitly convert type 'string' to 'System.Net.Mail.MailAddress'
var fromAddress = "device#***";
var toAddress = "*****#gmail.com";
const string fromPassword = "******";
var subject = "New Project Started!";
string body = "<b>TA:</b>";
MailMessage mail= new MailMessage();
mail.From = fromAddress;
mail.To = toAddress;
mail.Subject = subject;
mail.IsBodyHtml = true;
mail.Body = body;
var smtp = new System.Net.Mail.SmtpClient();
{
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.EnableSsl = true;
smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtp.Credentials = new NetworkCredential(fromAddress, fromPassword);
smtp.Timeout = 20000;
}
smtp.Send(mail);
EDITED:
My working solution:
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
var fromAddress = "****"; // mail Address from where you send the mail
var toAddress = "****";
const string fromPassword = "***"; //Password of your gmail address
var subject = "New Job Created!";
// set smtp-client with basicAuthentication
SmtpClient mySmtpClient = new SmtpClient("smtp.gmail.com");
mySmtpClient.Port = 587;
mySmtpClient.EnableSsl = true;
mySmtpClient.UseDefaultCredentials = false;
System.Net.NetworkCredential basicAuthenticationInfo = new
System.Net.NetworkCredential(fromAddress, fromPassword);
mySmtpClient.Credentials = basicAuthenticationInfo;
// add from,to mailaddresses
MailAddress from = new MailAddress(fromAddress, "");
MailAddress to = new MailAddress(toAddress, "Devision");
MailMessage myMail = new System.Net.Mail.MailMessage(from, to);
// set subject and encoding
myMail.Subject = subject;
myMail.SubjectEncoding = System.Text.Encoding.UTF8;
// set body-message and encoding
myMail.Body = "<b>TEST</b>";
myMail.BodyEncoding = System.Text.Encoding.UTF8;
// text or html
myMail.IsBodyHtml = true;
mySmtpClient.Send(myMail);
Create MailMessage Class. The key thing is to specify that the Body of the is HTML this is done with property IsBodyHtml
MailMessage mail= new MailMessage();
mail.From = fromAddress;
mail.To = toAddress;
mail.Subject = subject;
mail.IsBodyHtml = true;
mail.Body = body;
//other stuff
smtp.Send(mail);

Send Email With C# (Cpanel Hosting)

I have bought a cPanel host and the SMTP server information is:
This is my code:
string smtpAddress = "mandane.hostcream.com";
int portNumber = 465;
bool enableSSL = true;
string emailFrom = "mahabadi#exirsec.ir";
string password = Authenitication.PassWord;
string emailTo = To.Text;
string subject = Subject.Text;
string body = Body.Text;
using (MailMessage mail = new MailMessage())
{
mail.From = new MailAddress(emailFrom);
mail.To.Add(emailTo);
mail.Subject = subject;
mail.Body = body;
mail.IsBodyHtml = true;
using (SmtpClient smtp = new SmtpClient(smtpAddress, portNumber))
{
smtp.Credentials = new NetworkCredential(emailFrom, password);
smtp.EnableSsl = enableSSL;
smtp.Send(mail);
}
}
When I run my code and click on the send button after 1 or 2 minutes this appears:
Additional information: Failure sending mail.
What am I doing wrong?
I think you missed something, try this:
SmtpClient smtpClient = new SmtpClient();
NetworkCredential smtpCredentials = new NetworkCredential("email from","password");
MailMessage message = new MailMessage();
MailAddress fromAddress = new MailAddress("email from");
MailAddress toAddress = new MailAddress("email to");
smtpClient.Host = "smpt host address";
smtpClient.Port = your_port;
smtpClient.EnableSsl = true;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = smtpCredentials;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.Timeout = 20000;
message.From = fromAddress;
message.To.Add(toAddress);
message.IsBodyHtml = false;
message.Subject = "example";
message.Body = "example";
smtpClient.Send(message);
It seems that you cannot reach Yahoo address on port 465, please check if this address reachable first because it appears to be a network issue.

Unable to decode danish characters for email

I have some code to send an email. data for email is coming from third party API, which will look like this å equivalent of it is danish character å. but email shows s å .
Is there any way i can transform this one in to correct?
My code to send mail is like this
SmtpClient client = new SmtpClient();
System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
foreach (string toEmail in toEmails.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries))
mail.To.Add(toEmail.Trim());
mail.Subject = subject;
mail.SubjectEncoding = System.Text.Encoding.UTF8;
mail.Body = body;
mail.BodyEncoding = System.Text.Encoding.UTF8;
mail.IsBodyHtml = isHtml;
mail.Priority = MailPriority.Normal;
if (attachments != null)
{
foreach (string key in attachments.Keys)
{
Attachment mailAttachment = new Attachment(attachments[key], key);
mail.Attachments.Add(mailAttachment);
}
}
client.Send(mail);
retValue = true;
Note: Fixed the issue by using L.B's answer . but i am still having some issues like
this. in my email body
Use HttpUtility or WebUtility class
var str = HttpUtility.HtmlDecode("å");
var str = WebUtility.HtmlDecode("å");

Categories