I can't understand why this code is not working. I get an error saying property can not be assigned
MailMessage mail = new MailMessage();
SmtpClient client = new SmtpClient();
client.Port = 25;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Host = "smtp.gmail.com";
mail.To = "user#hotmail.com"; // <-- this one
mail.From = "you#yourcompany.example";
mail.Subject = "this is a test email.";
mail.Body = "this is my test email body";
client.Send(mail);
mail.To and mail.From are readonly. Move them to the constructor.
using System.Net.Mail;
...
MailMessage mail = new MailMessage("you#yourcompany.example", "user#hotmail.com");
SmtpClient client = new SmtpClient();
client.Port = 25;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Host = "smtp.gmail.com";
mail.Subject = "this is a test email.";
mail.Body = "this is my test email body";
client.Send(mail);
This :
mail.To = "user#hotmail.com";
Should be:
mail.To.Add(new MailAddress("user#hotmail.com"));
Finally got working :)
using System.Net.Mail;
using System.Text;
...
// Command line argument must the the SMTP host.
SmtpClient client = new SmtpClient();
client.Port = 587;
client.Host = "smtp.gmail.com";
client.EnableSsl = true;
client.Timeout = 10000;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential("user#gmail.com","password");
MailMessage mm = new MailMessage("donotreply#domain.example", "sendtomyemail#domain.example", "test", "test");
mm.BodyEncoding = UTF8Encoding.UTF8;
mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
client.Send(mm);
sorry about poor spelling before
public static void SendMail(MailMessage Message)
{
SmtpClient client = new SmtpClient();
client.Host = "smtp.googlemail.com";
client.Port = 587;
client.UseDefaultCredentials = false;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.EnableSsl = true;
client.Credentials = new NetworkCredential("myemail#gmail.com", "password");
client.Send(Message);
}
This is how it works for me. Hope you find it useful
MailMessage objeto_mail = new MailMessage();
SmtpClient client = new SmtpClient();
client.Port = 25;
client.Host = "smtp.internal.mycompany.com";
client.Timeout = 10000;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential("user", "Password");
objeto_mail.From = new MailAddress("from#server.com");
objeto_mail.To.Add(new MailAddress("to#server.com"));
objeto_mail.Subject = "Password Recover";
objeto_mail.Body = "Message";
client.Send(objeto_mail);
First go to https://myaccount.google.com/lesssecureapps and make Allow less secure apps true.
Then use the below code. This below code will work only if your from email address is from gmail.
static void SendEmail()
{
string mailBodyhtml =
"<p>some text here</p>";
var msg = new MailMessage("from#gmail.com", "to1#gmail.com", "Hello", mailBodyhtml);
msg.To.Add("to2#gmail.com");
msg.IsBodyHtml = true;
var smtpClient = new SmtpClient("smtp.gmail.com", 587); //**if your from email address is "from#hotmail.com" then host should be "smtp.hotmail.com"**
smtpClient.UseDefaultCredentials = true;
smtpClient.Credentials = new NetworkCredential("from#gmail.com", "password");
smtpClient.EnableSsl = true;
smtpClient.Send(msg);
Console.WriteLine("Email Sent Successfully");
}
If you want to have your email and password not appear in your code and want your company email client server to use your windows credentials use below.
client.Credentials = CredentialCache.DefaultNetworkCredentials;
Source
This just worked for me as of March 2017.
Started with solution from above "Finally got working :)" which didn't work at first.
SmtpClient client = new SmtpClient();
client.Port = 587;
client.Host = "smtp.gmail.com";
client.EnableSsl = true;
client.Timeout = 10000;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential("<me>#gmail.com", "<my pw>");
MailMessage mm = new MailMessage(from_addr_text, to_addr_text, msg_subject, msg_body);
mm.BodyEncoding = UTF8Encoding.UTF8;
mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
client.Send(mm);
This answer features:
Using 'using' whenever possible (IDisposable interfaces)
Using Object initializers
Async Programming
Extract SmtpConfig to external class (adjust it to your needs)
Here's the extracted code:
public async Task SendAsync(string subject, string body, string to)
{
using (var message = new MailMessage(smtpConfig.FromAddress, to)
{
Subject = subject,
Body = body,
IsBodyHtml = true
})
{
using (var client = new SmtpClient()
{
Port = smtpConfig.Port,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Host = smtpConfig.Host,
Credentials = new NetworkCredential(smtpConfig.User, smtpConfig.Password),
})
{
await client.SendMailAsync(message);
}
}
}
Class SmtpConfig:
public class SmtpConfig
{
public string Host { get; set; }
public string User { get; set; }
public string Password { get; set; }
public int Port { get; set; }
public string FromAddress { get; set; }
}
MailMessage mm = new MailMessage(txtEmail.Text, txtTo.Text);
mm.Subject = txtSubject.Text;
mm.Body = txtBody.Text;
if (fuAttachment.HasFile)//file upload select or not
{
string FileName = Path.GetFileName(fuAttachment.PostedFile.FileName);
mm.Attachments.Add(new Attachment(fuAttachment.PostedFile.InputStream, FileName));
}
mm.IsBodyHtml = false;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
NetworkCredential NetworkCred = new NetworkCredential(txtEmail.Text, txtPassword.Text);
smtp.UseDefaultCredentials = true;
smtp.Credentials = NetworkCred;
smtp.Port = 587;
smtp.Send(mm);
Response.write("Send Mail");
View Video:
https://www.youtube.com/watch?v=bUUNv-19QAI
smtp.Host = "smtp.gmail.com"; // the host name
smtp.Port = 587; //port number
smtp.EnableSsl = true; //whether your smtp server requires SSL
smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtp.Credentials = new NetworkCredential(fromAddress, fromPassword);
smtp.Timeout = 20000;
Go through this article for more details
Just need to try this:
string smtpAddress = "smtp.gmail.com";
int portNumber = 587;
bool enableSSL = true;
string emailFrom = "companyemail";
string password = "password";
string emailTo = "Your email";
string subject = "Hello!";
string body = "Hello, Mr.";
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);
}
MailKit is an Open Source cross-platform .NET mail-client library that is based on MimeKit and optimized for mobile devices.
It has more and advance features better than System.Net.Mail
Microsoft TNEF support via MimeKit.
Download nuget package from here.
See this example you can send mail
MimeMessage mailMessage = new MimeMessage();
mailMessage.From.Add(new MailboxAddress(senderName, sender#address.com));
mailMessage.Sender = new MailboxAddress(senderName, sender#address.com);
mailMessage.To.Add(new MailboxAddress(emailid, emailid));
mailMessage.Subject = subject;
mailMessage.ReplyTo.Add(new MailboxAddress(replyToAddress));
mailMessage.Subject = subject;
var builder = new BodyBuilder();
builder.TextBody = "Hello There";
try
{
using (var smtpClient = new SmtpClient())
{
smtpClient.Connect("HostName", "Port", MailKit.Security.SecureSocketOptions.None);
smtpClient.Authenticate("user#name.com", "password");
smtpClient.Send(mailMessage);
Console.WriteLine("Success");
}
}
catch (SmtpCommandException ex)
{
Console.WriteLine(ex.ToString());
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
Initialize the MailMessage with sender and reciever's email addresses. It should be something like
string from = "codeforwin#gmail.com"; //Senders email
string to = "reciever#gmail.com"; //Receiver's email
MailMessage msg = new MailMessage(from, to);
Read the full code snippet of how to send emails in c#
this would work too..
string your_id = "your_id#gmail.com";
string your_password = "password";
try
{
SmtpClient client = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
Credentials = new System.Net.NetworkCredential(your_id, your_password),
Timeout = 10000,
};
MailMessage mm = new MailMessage(your_iD, "recepient#gmail.com", "subject", "body");
client.Send(mm);
Console.WriteLine("Email Sent");
}
catch (Exception e)
{
Console.WriteLine("Could not end email\n\n"+e.ToString());
}
//Hope you find it useful, it contain too many things
string smtpAddress = "smtp.xyz.com";
int portNumber = 587;
bool enableSSL = true;
string m_userName = "support#xyz.com";
string m_UserpassWord = "56436578";
public void SendEmail(Customer _customers)
{
string emailID = gghdgfh#gmail.com;
string userName = DemoUser;
string emailFrom = "qwerty#gmail.com";
string password = "qwerty";
string emailTo = emailID;
// Here you can put subject of the mail
string subject = "Registration";
// Body of the mail
string body = "<div style='border: medium solid grey; width: 500px; height: 266px;font-family: arial,sans-serif; font-size: 17px;'>";
body += "<h3 style='background-color: blueviolet; margin-top:0px;'>Aspen Reporting Tool</h3>";
body += "<br />";
body += "Dear " + userName + ",";
body += "<br />";
body += "<p>";
body += "Thank you for registering </p>";
body += "<p><a href='"+ sURL +"'>Click Here</a>To finalize the registration process</p>";
body += " <br />";
body += "Thanks,";
body += "<br />";
body += "<b>The Team</b>";
body += "</div>";
// this is done using using System.Net.Mail; & using System.Net;
using (MailMessage mail = new MailMessage())
{
mail.From = new MailAddress(emailFrom);
mail.To.Add(emailTo);
mail.Subject = subject;
mail.Body = body;
mail.IsBodyHtml = true;
// Can set to false, if you are sending pure text.
using (SmtpClient smtp = new SmtpClient(smtpAddress, portNumber))
{
smtp.Credentials = new NetworkCredential(emailFrom, password);
smtp.EnableSsl = enableSSL;
smtp.Send(mail);
}
}
}
send email by smtp
public void EmailSend(string subject, string host, string from, string to, string body, int port, string username, string password, bool enableSsl)
{
try
{
MailMessage mail = new MailMessage();
SmtpClient smtpServer = new SmtpClient(host);
mail.Subject = subject;
mail.From = new MailAddress(from);
mail.To.Add(to);
mail.Body = body;
smtpServer.Port = port;
smtpServer.Credentials = new NetworkCredential(username, password);
smtpServer.EnableSsl = enableSsl;
smtpServer.Send(mail);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
ERROR: Service not available, closing transmission channel. The server response was: Resources temporarily unavailable - Please try again later
private void button1_Click(object sender, EventArgs e)
{
string smtpAddress = "smtp.mail.yahoo.com";
int portNumber = 587;
bool enableSSL = true;
string emailFrom = "mail#yahoo.com";
string password = "mailpass";
string emailTo = "sendemail#yahoo.com";
string subject = "Hello";
string body = "Hello, I'm just writing this to say Hi!";
using (MailMessage mail = new MailMessage())
{
mail.From = new MailAddress(emailFrom);
mail.To.Add(emailTo);
mail.Subject = subject;
mail.Body = body;
//mail.IsBodyHtml = true;
// Can set to false, if you are sending pure text.
// mail.Attachments.Add(new Attachment("C:\\SomeFile.txt"));
//mail.Attachments.Add(new Attachment("C:\\SomeZip.zip"));
using (SmtpClient smtp = new SmtpClient(smtpAddress, portNumber))
{
smtp.Credentials = new NetworkCredential(emailFrom, password);
smtp.EnableSsl = enableSSL;
smtp.Send(mail);
}
}
}
What should I do?
You need to make sure an external application has permission to send emails through your email before you can proceed.
I am setting up mail sending in my code as below
NetworkCredential nc = new NetworkCredential(ConfigurationManager.AppSettings["EmailId"].ToString(), ConfigurationManager.AppSettings["Password"].ToString());
MailMessage mm = new MailMessage();
mm.From = new MailAddress(SendEmailaddress);
mm.Body = "Test Mail";
mm.IsBodyHtml = true;
mm.BodyEncoding = System.Text.Encoding.UTF8;
mm.To.Add(ToEmailAddress);
mm.Subject = "Test";
SmtpClient sp = new SmtpClient();
sp.UseDefaultCredentials = false;
sp.Credentials = nc;
sp.EnableSsl = true;
sp.DeliveryMethod = SmtpDeliveryMethod.Network;
sp.Port = 587
sp.Host = ConfigurationManager.AppSettings["SMTP"].ToString();
sp.Send(mm);
A error is thrown at the time of mail sending. Mail sending works if I configure outlook on the same PC with these settings with TLS as encrypted connnection.
I have checked many posts where it is suggested that EnableSsl = true should be set for TLS to work but it does not work for me. It throws below error
Transaction failed. The server response was: 5.7.1
: Recipient address rejected: Access denied
at System.Net.Mail.RecipientCommand.CheckResponse(SmtpStatusCode
statusCode, String response) at
System.Net.Mail.SmtpTransport.SendMail(MailAddress sender,
MailAddressCollection recipients, String deliveryNotify,
SmtpFailedRecipientException& exception) at
System.Net.Mail.SmtpClient.Send(MailMessage message)
I have hit a roadblock as no solution is found. is there a setting which needs to be done on server?
protected void SendAlertEmail(string smtpserver, string smtpport, string smtpuser, string smtppass, int ssl, int auth, string subject, string from, string to, string body)
{
try
{
MailMessage mail = new MailMessage();
mail.From = new MailAddress(SplitEmailStrging(from), HttpUtility.HtmlDecode(Request.Form["senderName"]));
string emails = to;
if (emails.Contains(","))
{
string[] emailslist = Regex.Split(emails, #",");
foreach (string email in emailslist)
{
mail.To.Add(SplitEmailStrging(email));
}
}
else
{
if (emails.Contains("<"))
{
mail.To.Add(SplitEmailStrging(emails));
// Response.Write(SplitEmailStrging(emails));
}
else
{
mail.To.Add(emails);
// Response.Write(emails);
}
}
mail.Subject = subject;
mail.IsBodyHtml = true;
mail.Body = HttpUtility.HtmlDecode(body);
SmtpClient client = new SmtpClient(smtpserver);
if (int.Parse(smtpport) == 465)
{
client.Port = 25;
}
else
{
client.Port = int.Parse(smtpport);
}
if (ssl == 1)
{
client.EnableSsl = true;
}
else
{
client.EnableSsl = false;
}
client.DeliveryMethod = SmtpDeliveryMethod.Network;
System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(smtpuser, smtppass);
client.UseDefaultCredentials = false;
client.Credentials = credentials;
client.Send(mail);
}
catch (Exception ex)
{
Response.Write("Error: " + ex.InnerException.Message);
Response.End();
}
}
public void SendEmailWithAttachment(string pFrom, string pTo, string pSubject, string pBody, string pServer, string strAttachmentPDFFileNames)
{
try
{
System.Net.Mail.MailMessage Message = new System.Net.Mail.MailMessage();
string UserName = ConfigurationManager.AppSettings["SMTPUserName"];
string Password = ConfigurationManager.AppSettings["SMTPPassword"];
if (pTo.Contains(","))
{
string[] ToAdd = pTo.Split(new Char[] { ',' });
for (int i = 0; i < ToAdd.Length; i++)
{
Message.To.Add(ToAdd[i]);
}
}
else
{
Message.To.Add(pTo);
}
//System.Net.Mail.MailAddress toAddress = new System.Net.Mail.MailAddress(pTo);
//Message.To.Add(toAddress);
System.Net.Mail.MailAddress fromAddress = new System.Net.Mail.MailAddress(pFrom);
Message.From = fromAddress;
Message.Subject = pSubject;
Message.Body = pBody;
Message.IsBodyHtml = true;
// Stream streamPDFImages = new MemoryStream(bytPDFImageFile);
//System.Net.Mail.SmtpClient
var smtpClient = new System.Net.Mail.SmtpClient();
{
Message.Attachments.Add(new System.Net.Mail.Attachment(strAttachmentPDFFileNames));
smtpClient.EnableSsl = true;
smtpClient.Host = pServer;
smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtpClient.Credentials = new System.Net.NetworkCredential(UserName, Password);
smtpClient.Port = 465;
smtpClient.Send(Message);
}
}
catch (Exception Exc)
{
Exception ex = new Exception("Unable to send email . Please Contact administrator", Exc);
throw ex;
}
}
SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential("yourMail", "yourPassword");
smtp.EnableSsl = true;
MailMessage msg = new MailMessage(sendFrom, "yourMail");
msg.ReplyToList.Add(sendFrom);
msg.Subject = subject;
msg.Body = bodyTxt;
System.Net.Mail.Attachment attachment = new System.Net.Mail.Attachment(#"C:\Projects\EverydayProject\test.txt");
msg.Attachments.Add(attachment);
smtp.Send(msg);
Here is working code to send an email to gmail smtp. From what I see you don't set UseDefaultCredentials = false and you are using wrong port. Also you MUST NOT override exceptions like this., throw the initial exception. Also for this to work you need to turn off security setting in your Gmail account. You can google it.
I have write C# code to send mail (my company mail). I tried with gmail and it working but with my company mail is not.
I sure the smtp server is running and port 465 opened since I can send mail by outlook 2k7 with the same account, telnet smtp.domain 465 ok.
When i run the code it throw exception "System.Net.Mail.SmtpException: The operation has time out."
Here is my c# code:
var fromAddress = new MailAddress("ID#domain", "Display Name");
var toAddress = new MailAddress("ID#domain", "Display Name");
const string subject = "Test mail";
const string body = "Test mail";
var smtp = new SmtpClient
{
Host = "smtp.domain",
Port = 465,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential("ID", "pass"),
Timeout=15000
};
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body,
})
{
try
{
smtp.Send(message);
MessageBox.Show("OK");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
Any one know or have same problem that fixed please help me. Thanks so much!
Try changing setting EnableSsl = false in your SmtpClient instance.
You can change this code and reuse this code:
public static void sendEmail(string address, string subject, string message)
{
string email = "yourEmail";
string password = "yourPass";
var loginInfo = new NetworkCredential(email, password);
var msg = new MailMessage();
var smtpClient = new SmtpClient("smtp.gmail.com", portNumber);
msg.From = new MailAddress(email);
msg.To.Add(new MailAddress(address));
msg.Subject = subject;
msg.Body = message;
msg.IsBodyHtml = true;
smtpClient.EnableSsl = true;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = loginInfo;
smtpClient.Send(msg);
}