I'm sending e-mails with System.Net.Mail.SmtpClient. The problem is that when I add an attachment to the MailMessage the received e-mails subject and the attached filenames decoding goes wrong.
When the subject or attachment name string contains only one special character like 'ü' the decoding fails, but if it contains more like 'ÍŰÁÉÚŐÓÜÖíűáéúőóüö' the decoding is ok.
Code to reproduce the problem:
var message = new MailMessage();
message.From = new MailAddress("test#test.com", "test");
message.To.Add(new MailAddress("test#test.com", "test"));
message.Subject = "Teszt üzenet";
message.Body = "Teszt üzenet";
// if i remove the line below en/decoding is ok
message.Attachments.Add(new Attachment(#"document.pdf") { Name = "fájl.pdf" });
using (var smtp = new SmtpClient() {
DeliveryFormat = SmtpDeliveryFormat.International,
DeliveryMethod = SmtpDeliveryMethod.Network,
EnableSsl = Settings.UseSsl,
Host = Settings.Host,
Port = Settings.Port,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(Settings.Username, Settings.Password)
}) {
smtp.Send(message);
}
Setting message.SubjectEcoding and others doesn't seem to matter. The default is UTF-8 which i would use anyway.
I'm using gmail smtp for testing and this is part of a webapi 2 project.
The reason for the encoding/decoding failures was the gmail smtp.
Related
Having researched the issue extensively especially applying recommendations from similar issues on stackoverflow, the below code still returns error ""System.Net.Mail.SmtpException: Syntax error, command unrecognized. The server response was: connection rejected at....""
try
{
var mail = new MailMessage();
mail.From = new MailAddress("demo77377#gmail.com");
mail.To.Add(new MailAddress("xxxxxxx#gmail.com"));
mail.Subject = "TEST";
mail.Body = "This is a test mail from C# program";
using (var smtp = new SmtpClient())
{
smtp.Credentials = new System.Net.NetworkCredential("demo77377#gmail.com", "AABBCCDDEE1!","gmail.com");
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.EnableSsl = true;
smtp.UseDefaultCredentials = false;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.Timeout = 10000;
//
smtp.Send(mail);
Console.WriteLine("Message sent successfully");
Console.ReadLine();
}
}
catch (Exception e)
I have done everything possible
On Client> I have alternated smtp properties (permutation) etc
On Server> I have made gmail account less secure, I have disabled captcha etc
I observed that similar issues on stackoverflow were mostly dated over 3years ago and thus, is it possible that gmail no longer supports this SMTP method via C#, likewise has it been deprecated in favor of gmail API
Also, please find provided in code, original password supplied for the gmail account, in order to confirm if this issue is general or isolated to this gmail account
Thanks
This code is verified to work fine:
var fromAddress = new MailAddress("YOUREMAIL#gmail.com", "YOUREMAIL#gmail.com");
var toAddress = new MailAddress("YOUREMAIL#gmail.com", "YOUREMAIL#gmail.com");
const string fromPassword = "YOURPASSWORD";
const string subject = "YOUREMAIL#gmail.com";
const string body = "YOUREMAIL#gmail.com";
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(fromAddress.Address, fromPassword),
Timeout = 20000
};
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body
})
{
smtp.Send(message);
}
I'm not comfortable including your personal details even though you have so I have removed them. Obviously replace the email and password with the correct details.
Finally got it working after switching from my hotel's wireless network to office network...type of network connection has a role to play in sending email via SMTP in C#
I'm trying to send email from asp.net mvc controller. Gmail account used here for smpt is configured to use with less security, so that's not the problem here.
but I don't get any error message neither any exception, but it not
deliver at my expected email address.
I'm using code
var text = "email body to deliver";
SendEmail("mydeliverEmailAddress#gmail.com", text);
public static bool SendEmail(string SentTo, string Text)
{
SmtpClient client = new SmtpClient();
client.Credentials = new NetworkCredential("myemail#gmail.com", "myGmailPass");
client.Port = 465;
client.Host = "smtp.gmail.com";
client.EnableSsl = true;
try
{
MailAddress
maFrom = new MailAddress("sender_email#domain.tld", "Sender's Name", Encoding.UTF8),
maTo = new MailAddress(SentTo, "Recipient's Name", Encoding.UTF8);
MailMessage mmsg = new MailMessage(maFrom.Address, maTo.Address);
mmsg.Body = "<html><body><h1>Some HTML Text for Test as BODY</h1></body></html>";
mmsg.IsBodyHtml = true;
mmsg.Subject = "Some Other Text as Subject";
mmsg.SubjectEncoding = Encoding.UTF8;
client.Send(mmsg);
}
catch (Exception ex)
{
}
return true;
}
Wait a minute. You are using your gmail account: myemail#gmail.com and trying to send an email on behalf of sender_email#domain.tld?
For more than obvious reasons that's never gonna work. So make sure that you are using the same email address as the one you are authenticating against:
maFrom = new MailAddress("myemail#gmail.com", "Sender's Name", Encoding.UTF8),
You can only send emails from the account you are authenticated against. Of course the recipient email can be any address that gmail can deliver to.
You've got another issue with your code. You are using a wring port here:
client.Port = 465;
The correct port that gmail SMTP works with is the following:
client.Port = 587;
Also you might want to ensure that you have enabled less secure apps in your gmail account or you will not be able to use SmtpClient in .NET to send emails using this SMTP: https://www.google.com/settings/security/lesssecureapps?pli=1
but I don't get any error message neither any exception, but it not
deliver at my expected email address.
What error message do you expect to get when you did the worst ever possible thing? You wrapped your code in a try/catch block and in your catch block you did absolutely nothing. You just consumed the exception:
catch (Exception ex)
{
}
So make sure that you do something useful with an exception if you are going to be catching it. For example something useful could be to log this exception and send an error message to the user saying that something bad happened and you couldn't send an email and that you are investigating the issue right now.
var smtpClient = new SmtpClient("YourSMTPServer", "SMTPServerPort"))
{
Credentials = new NetworkCredential("YourEmail",
"Password"),
EnableSsl = false
};
string fromEmail = "YourEmail";
var mailMessage = new MailMessage();
mailMessage.From = new MailAddress(fromEmail);
mailMessage.To.Add("Recipient's EMail");
mailMessage.Subject = "Test Mail";
mailMessage.Body = "This is test Mail";
mailMessage.IsBodyHtml = true;
smtpClient.Send(mailMessage);
I'm trying to send emails using gmail's username and password in a Windows application. However, the following code is sending the mail to only the first email address when I collect multiple email address in my StringBuilder instance.
var fromAddress = new MailAddress(username, DefaultSender);
var toAddress = new MailAddress(builder.ToString());//builder reference having multiple email address
string subject = txtSubject.Text;
string body = txtBody.Text; ;
var smtp = new SmtpClient
{
Host = HostName,
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(username, password),
//Timeout = 1000000
};
var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body,
IsBodyHtml = chkHtmlBody.Checked
};
if (System.IO.File.Exists(txtAttechments.Text))
{
System.Net.Mail.Attachment attechment = new Attachment(txtAttechments.Text);
message.Attachments.Add(attechment);
}
if(this.Enabled)
this.Enabled = false;
smtp.Send(message);
What am I doing wrong, and how can I sort out my problem?
Best bet is to message.To.Add() each of your MailAddresses individually. I think early versions of .Net were happier to parse apart comma or semicolon separated email addresses than the more recent runtime versions.
I was having the same problem.
The code is actually
message.To.Add("xxx#gmail.com, yyy#gmail.com");
this one can work in .net 3.5
if you use
message.To.Add( new MailAddress("xxx#gmail.com, yyy#gmail.com"));
this won't work in .net 3.5
In this post Sending Email in .NET Through Gmail we have a code to send email through gmail, in the send mail we find from Field contain gmail account that I used
I use the same code but by changing the From Address to any email I want ans set gmail address in Credentials as bellow
var fromAddress = new MailAddress("AnyEmai#mailserver.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("from#gmail.com", fromPassword)
};
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body
})
{
smtp.Send(message);
}
But in the sent email gmail account still appear in From Address and AnyEmai#mailserver.com not appear ... is there any way to do that ?
It's that way by design. You have to find another way to send outbound emails so that the return address you want shows up (I've been there, there seems to be no way to spoof the from address).
Shall you check this question change sender address when sending mail through gmail in c#
I think it is related to your inquiry.
You can import an email id in your gmail account using Mail Settings >> Accounts and Import options and that can be used for sending the mails, however if you are want to use some random email id everytime to send the mails it is not possible. Gmail will treat that as a spoofing/spam and it will reset the mail address to your original mail id before sending the mail.
using System.Net;
using System.Net.Mail;
public void email_send()
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("from#gmail.com");
mail.To.Add("to#gmail.com");
mail.Subject = "Your Subject";
mail.Body = "Body Content goes here";
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment("c:/file.txt");
mail.Attachments.Add(attachment);
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("from#gmail.com", "mailpassword");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
}
There are many other mail services from which you can achieve the same but not through the gmail. Checkout the blog Send email in .NET through Gmail for sending mail using different properties.
The email address needed to be verified by gmail from the account settings.
Please find my blog post for the same describing it in detail, the steps to be followed:
http://karmic-development.blogspot.in/2013/10/send-email-from-aspnet-using-gmail-as.html
before following all the above steps, you need to authenticate your gmail account to allow access to your application and also the devices. Please check all the steps for account authentication at the following link:
http://karmic-development.blogspot.in/2013/11/allow-account-access-while-sending.html
I've found this small code that sends email to gmail users. I'd like the body of the mail to contain html (for example, decoding a link for it to hold different text than the url it's pointing to).
I am using c# .net 3.5. I've used these classes in my code:
MailMessage
SmtpClient
How can this be done?
Here's a copy of my code:
MailMessage message = new MailMessage("me#gmail.com", WebCommon.UserEmail, "Test", context.Server.HtmlEncode("<html> <body> <a href='www.cnn.com'> test </a> </body> </html> "));
System.Net.NetworkCredential cred = new System.Net.NetworkCredential("him#gmail.com", "myPwd");
message.IsBodyHtml = true;
System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("smtp.gmail.com");
smtp.UseDefaultCredentials = false;
smtp.EnableSsl = true;
smtp.Credentials = cred;
smtp.Port = 587;
smtp.Send(message);
Thanks!
Something like this should work:
Note that MailMessage refers to System.Net.MailMessage. There is also System.Web.MailMessage, which I have never used and -as far as I know- is obsolete.
MailMessage message = new MailMessage();
// Very basic html. HTML should always be valid, otherwise you go to spam
message.Body = "<html><body><p>test</p></body></html>";
// QuotedPrintable encoding is the default, but will often lead to trouble,
// so you should set something meaningful here. Could also be ASCII or some ISO
message.BodyEncoding = Encoding.UTF8;
message.IsBodyHtml = true;
// No Subject usually goes to spam, too
message.Subject = "Some Subject";
// Note that you can add multiple recipients, bcc, cc rec., etc. Using the
// address-only syntax, i.e. w/o a readable name saves you from some issues
message.To.Add("someone#gmail.com");
// SmtpHost, -Port, -User, -Password must be a valid account you can use to
// send messages. Note that it is very often required that the account you
// use also has the specified sender address associated!
// If you configure the Smtp yourself, you can change that of course
SmtpClient client = new SmtpClient(SmtpHost, SmtpPort) {
Credentials = new NetworkCredential(SmtpUser, SmtpPassword),
EnableSsl = enableSsl;
};
try {
// It might be necessary to enforce a specific sender address, see above
if (!string.IsNullOrEmpty(ForceSenderAddress)) {
message.From = new MailAddress(ForceSenderAddress);
}
client.Send(message);
}
catch (Exception ex) {
return false;
}
For more sophisticated templating solutions that render the Body html rather than hard-codin it, there is, for example, the EMailTemplateService in MvcContrib which you can use as a guideline.
One way to do it is to create an alternate html view of the email:
MailMessage message = new MailMessage();
message.Body = //plain-text version of message
//set up message...
//create html view
string htmlBody = "<html>...</html>";
htmlView = AlternateView.CreateAlternateViewFromString(htmlBody, null, "text/html");
message.AlternateViews.Add(htmlView);
//send message
smtpClient.Send(message);