.Net send mail through Gmail [duplicate] - c#

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Sending email in .NET through Gmail
I am trying to send a mail with Asp.Net (MVC3) through an GMail-account i've created. I've crawled the internet for how-to's, but nothing i tried has been working.
I have a method that looks like this
public static bool SendEmail(string to,string subject,string body)
{
try
{
MailMessage mail = new MailMessage();
mail.From = new MailAddress("myaccount#gmail.com");
mail.To.Add(to);
mail.Subject = subject;
mail.Body = body;
mail.IsBodyHtml = false;
SmtpClient smtp = new SmtpClient();
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.Credentials = new System.Net.NetworkCredential("myaccount#gmail.com", "mypassword");
smtp.EnableSsl = true;
smtp.Send(mail);
return true;
}
catch
{
return false;
}
}
This method returns false when im using it. How can i solve this?

I verified the following works:
static void Main(string[] args)
{
//create the mail message
MailMessage mail = new MailMessage();
var client = new SmtpClient("smtp.gmail.com", 587)
{
Credentials = new NetworkCredential("your.email#gmail.com", "yourpassword"),
EnableSsl = true
};
//set the addresses
mail.From = new MailAddress("your.email#gmail.com");
mail.To.Add("to#wherever.com");
//set the content
mail.Subject = "Test subject!";
mail.Body = "<html><body>your content</body></html>";
mail.IsBodyHtml = true;
client.Send(mail);
}

Try Adding this line
smtp.UseDefaultCredentials = false;

Related

How to fix unstable smtp mail service?

I have an ASP.NET Core 3.1 Web API project. I am using Entity Framework.
When I pass data statically to a smtp client, mail is sent and there is no problem:
SmtpClient smtp = new SmtpClient();
smtp.UseDefaultCredentials = false;
smtp.Credentials = new System.Net.NetworkCredential("development#mail.com.tr", "password");
smtp.Port = 587;
smtp.Host = "mail.com.tr";
smtp.EnableSsl = false;
MailMessage mail = new MailMessage();
mail.To.Add("atakan#mail.com.tr");
mail.From = new MailAddress("development#mail.com.tr");
mail.Subject = PostaSubject;
mail.IsBodyHtml = true;
mail.Body = MailTemplate(subject, subject);
smtp.Send(mail);
But when I get the smtp client data from the data in the context, sometimes the mail is sent, sometimes it cannot be thrown and it works unstable. How can I fix it?
SmtpClient smtp = new SmtpClient();
smtp.UseDefaultCredentials = false;
smtp.Credentials = new System.Net.NetworkCredential(_context.MailConfigs.Select(x => x.UserName).FirstOrDefault(), _context.MailConfigs.Select(x => x.UserPassword).FirstOrDefault());
smtp.Port = (int)_context.MailConfigs.Select(x => x.SmtpPort).FirstOrDefault();
smtp.Host = _context.MailConfigs.Select(x => x.SmtpHost).FirstOrDefault();
smtp.EnableSsl = false;
MailMessage mail = new MailMessage();
mail.To.Add(_context.MailConfigs.Select(x => x.Reciever).FirstOrDefault());
mail.From = new MailAddress(_context.MailConfigs.Select(x => x.UserName).FirstOrDefault());
mail.Subject = PostaSubject;
mail.IsBodyHtml = true;
mail.Body = MailTemplate(subject, subject);
smtp.Send(mail);
FirstOrDefault will return a value or null, why not use a string variable to capture the value of FirstOrDefault result and if it is not null then send the email or if the value is null then just ignore or write to a log.

Sending and Receiving mail to MS Exchange via SMTPClient [duplicate]

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

Not able to send emails through my asp.net application

I am getting Time-out Error.
I am not able to send email using this code. I tried almost every
possible way but of no use.
try
{
string myString = "Hello I am new email message. I am delivered for testing.";
MailMessage mm = new MailMessage("XXXXXXXXXX", "XXXXXXXXXX");
//mm.CC.Add("XXXXXXXXXX");
mm.Subject = "Subject have been successfully placed.";
mm.Body = myString.ToString();
mm.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
NetworkCred.UserName = "XXXXXXXXXX";
NetworkCred.Password = "XXXXXXXXXX";
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.UseDefaultCredentials = true;
smtp.Credentials = NetworkCred;
smtp.Port = 465;
smtp.Send(mm);
Request.Cookies.Clear();
}
catch (Exception ee)
{
Response.Write(ee.Message);
}
try this
private void SendMail()
{
MailMessage mail = new MailMessage();
SmtpClient mailClient = new SmtpClient("smtp.gmail.com", 587);
mail.From = new MailAddress("Setfromaddress");
mail.To.Add(new MailAddress("recepient#gmail.com"));
mail.Subject = "Test";
mail.Body = "This is a test";
mailClient.EnableSsl = true;
mailClient.Credentials = new NetworkCredential("Username", "Password");
try
{
mailClient.Send(mail);
}
catch(Exception ex)
{
WriteErrorOutput(ex.Message);
}
}
also I think we need to check the connection
To run the telnet and test on a Windows in your computer:
1.Open the Start menu, and select Run.
2.Enter command in the Open: field, and click OK.
3.Enter 'telnet smtp.gmail.com 465,' and hit Enter, or enter 'telnet smtp.gmail.com 587' instead.

Sending a gmail email

I am trying to send an email through and C# application (Console). Actually I would like it to send an email to any type of email but for the time being if I can get it to send to a gmail account I would be happy enough.
I just want to be able to get this to send to a gmail account for the time being?
Whole Program:
namespace EmailAddress
{
class Program
{
static void Main(string[] args)
{
Program test = new Program();
test.email_send();
}
public void email_send()
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("hg#gmail.com");
mail.To.Add("hg#gmail.com");
mail.Subject = "Test Mail - 1";
mail.Body = "Your attachment is accessible on your computer!";
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment("g:/example1.txt");
mail.Attachments.Add(attachment);
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("your mail#gmail.com", "your password");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
}
}
}
New code: Doesn't hang but will not send the message to the inbox
static void Main(string[] args)
{
Program test = new Program();
//test.email_send();
test.CreateTestMessage4();
}
public void email_send()
{
MailMessage mail = new MailMessage();
SmtpClient smtp = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("g#gmail.com");
mail.To.Add("g#gmail.com");
mail.Subject = "Test Mail - 1";
mail.Body = "Your attachment is accessible on your computer!";
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment("g:\\example1.txt");
mail.Attachments.Add(attachment);//list of attachements
smtp.Port = 587;//google standard -- most of the time wouldn't not set
smtp.EnableSsl = true;
smtp.UseDefaultCredentials = true;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.Credentials = new System.Net.NetworkCredential("*","*");
smtp.Send(mail);
Console.WriteLine("-- Sending Email --");
Console.ReadLine();
}
Can someone try this code and see if it works. For some reason this isn't working so I would like to have someone's fresh perspective of this. I just call this in the main method for an instance of the class.
public void email_send()
{
MailMessage mail = new MailMessage();
SmtpClient smtp = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("your email address");
mail.To.Add("your email address");
mail.Subject = "Test Mail - 1";
mail.Body = "Your attachment is accessible on your computer!";
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment("g:\\example1.txt");
mail.Attachments.Add(attachment);//list of attachements
//smtp.Port = 587;//google standard -- most of the time wouldn't not set
//smtp.EnableSsl = true;
//smtp.UseDefaultCredentials = true;
//smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
//smtp.Credentials = new System.Net.NetworkCredential("your address",
"your password");
smtp.Port = 587;
smtp.Host = "smtp.gmail.com";
smtp.UseDefaultCredentials = false;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.EnableSsl = true;
smtp.Credentials = new System.Net.NetworkCredential("*", "*"); smtp.Send(mail);
Console.WriteLine("-- Sending Email --");
Console.ReadLine();
}
Your code is close:
MailMessage mail = new MailMessage();
using (SmtpClient smtp = new SmtpClient("smtp.gmail.com")) {
mail.From = new MailAddress("haufdoug#gmail.com");
mail.To.Add("haufdoug#gmail.com");
mail.Subject = "Test Mail - 1";
mail.Body = "Your attachment is accessible on your computer!";
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment("g:\\example1.txt");
mail.Attachments.Add(attachment);
smtp.Port = 587;
smtp.EnableSsl = true;
smtp.UseDefaultCredentials = false;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.Credentials = new System.Net.NetworkCredential("your mail#gmail.com", "your password");
smtp.Send(mail);
}
Now, regarding some of your other questions.
Port 587 is used by Google only. Typically the mail server you connect to will tell you what port to use for SMTP mail; Google said there's is 587.
For sending through other servers you typically won't set the port number.
side notes:
SmtpClient implements the IDisposable interface. So it should be wrapped in a using clause to ensure it is properly disposed of when complete. Unless you are using the .SendAsync() method.
I changed the variable name from SmtpServer to smtp for two reasons. First, naming convention. Variables inside a method are recommended to be camel case (forExampleThis). Second, SmtpServer is a misnomer as the object is an SmtpClient. Those are very different things and it's just bad practice to misname things.
Can you try this, it's working for me:
SmtpClient SmtpServer = new SmtpClient();
SmtpServer.Port = 587;
SmtpServer.Host = smtp.gmail.com;
SmtpServer.UseDefaultCredentials = false;
SmtpServer.DeliveryMethod = SmtpDeliveryMethod.Network;
SmtpServer.EnableSsl = true;
SmtpServer.Credentials = new System.Net.NetworkCredential("your mail#gmail.com", "your password");

Send email using System.Net.Mail through gmail

I want to send a email through gmail server. I have put the following code but it is getting stuck while sending. Any idea please....
MailMessage mail = new MailMessage();
mail.From = new System.Net.Mail.MailAddress("apps#xxxx.com");
//create instance of smtpclient
SmtpClient smtp = new SmtpClient();
smtp.Port = 465;
smtp.UseDefaultCredentials = true;
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
//recipient address
mail.To.Add(new MailAddress("yyyy#xxxx.com"));
//Formatted mail body
mail.IsBodyHtml = true;
string st = "Test";
mail.Body = st;
smtp.Send(mail);
The xxxx.com is a mail domain in Google apps.
Thanks...
MailMessage mail = new MailMessage();
mail.From = new System.Net.Mail.MailAddress("apps#xxxx.com");
// The important part -- configuring the SMTP client
SmtpClient smtp = new SmtpClient();
smtp.Port = 587; // [1] You can try with 465 also, I always used 587 and got success
smtp.EnableSsl = true;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network; // [2] Added this
smtp.UseDefaultCredentials = false; // [3] Changed this
smtp.Credentials = new NetworkCredential(mail.From, "password_here"); // [4] Added this. Note, first parameter is NOT string.
smtp.Host = "smtp.gmail.com";
//recipient address
mail.To.Add(new MailAddress("yyyy#xxxx.com"));
//Formatted mail body
mail.IsBodyHtml = true;
string st = "Test";
mail.Body = st;
smtp.Send(mail);
I tried the above C# code to send mail from Gmail to my Corporate ID. While executing the application the control stopped indefinitely at the statement smtp.Send(mail);
While Googling, I came across a similar code, that worked for me. I am posting that code here.
class GMail
{
public void SendMail()
{
string pGmailEmail = "fromAddress#gmail.com";
string pGmailPassword = "GmailPassword";
string pTo = "ToAddress"; //abc#domain.com
string pSubject = "Test From Gmail";
string pBody = "Body"; //Body
MailFormat pFormat = MailFormat.Text; //Text Message
string pAttachmentPath = string.Empty; //No Attachments
System.Web.Mail.MailMessage myMail = new System.Web.Mail.MailMessage();
myMail.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/smtpserver",
"smtp.gmail.com");
myMail.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/smtpserverport",
"465");
myMail.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/sendusing",
"2");
//sendusing: cdoSendUsingPort, value 2, for sending the message using
//the network.
//smtpauthenticate: Specifies the mechanism used when authenticating
//to an SMTP
//service over the network. Possible values are:
//- cdoAnonymous, value 0. Do not authenticate.
//- cdoBasic, value 1. Use basic clear-text authentication.
//When using this option you have to provide the user name and password
//through the sendusername and sendpassword fields.
//- cdoNTLM, value 2. The current process security context is used to
// authenticate with the service.
myMail.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1");
//Use 0 for anonymous
myMail.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/sendusername",
pGmailEmail);
myMail.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/sendpassword",
pGmailPassword);
myMail.Fields.Add
("http://schemas.microsoft.com/cdo/configuration/smtpusessl",
"true");
myMail.From = pGmailEmail;
myMail.To = pTo;
myMail.Subject = pSubject;
myMail.BodyFormat = pFormat;
myMail.Body = pBody;
if (pAttachmentPath.Trim() != "")
{
MailAttachment MyAttachment =
new MailAttachment(pAttachmentPath);
myMail.Attachments.Add(MyAttachment);
myMail.Priority = System.Web.Mail.MailPriority.High;
}
SmtpMail.SmtpServer = "smtp.gmail.com:465";
SmtpMail.Send(myMail);
}
}
Set
smtp.UseDefaultCredentials = false
and use
smtp.Credentials = new NetworkCredential(gMailAccount, password);
This have worked for me:
MailMessage message = new MailMessage("myemail#gmail.com", toemail, subjectEmail, comments);
message.IsBodyHtml = true;
try {
SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
client.Timeout = 2000;
client.EnableSsl = true;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
//client.Credentials = CredentialCache.DefaultNetworkCredentials;
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential("myemail#gmail.com", "mypassord");
client.Send(message);
message.Dispose();
client.Dispose();
}
catch (Exception ex) {
Debug.WriteLine(ex.Message);
}
BUT (as of the time of this writing - Oct 2017)
You need to ENABLE "Allow less secure apps" inside the option "apps with account access" at the "My account" google security/privacy settings (https://myaccount.google.com)
I realise this is an answer to a very old question, with lots of other good answers. I am posting this code to include some of the useful comments posted by other users such as Using Statements and newer methods where some answers have obsolete methods. This code was tested and working as of 11 July 2018.
If sending via your GMail Account ensure that Allow less secure apps is enabled from your control panel
Class Code C#:
public class Email
{
public void NewHeadlessEmail(string fromEmail, string password, string toAddress, string subject, string body)
{
using (System.Net.Mail.MailMessage myMail = new System.Net.Mail.MailMessage())
{
myMail.From = new MailAddress(fromEmail);
myMail.To.Add(toAddress);
myMail.Subject = subject;
myMail.IsBodyHtml = true;
myMail.Body = body;
using (System.Net.Mail.SmtpClient s = new System.Net.Mail.SmtpClient("smtp.gmail.com", 587))
{
s.DeliveryMethod = SmtpDeliveryMethod.Network;
s.UseDefaultCredentials = false;
s.Credentials = new System.Net.NetworkCredential(myMail.From.ToString(), password);
s.EnableSsl = true;
s.Send(myMail);
}
}
}
}
Class Code VB:
Public Class Email
Sub NewHeadlessEmail(fromEmail As String, password As String, toAddress As String, subject As String, body As String)
Using myMail As System.Net.Mail.MailMessage = New System.Net.Mail.MailMessage()
myMail.From = New MailAddress(fromEmail)
myMail.To.Add(toAddress)
myMail.Subject = subject
myMail.IsBodyHtml = True
myMail.Body = body
Using s As New Net.Mail.SmtpClient("smtp.gmail.com", 587)
s.DeliveryMethod = SmtpDeliveryMethod.Network
s.UseDefaultCredentials = False
s.Credentials = New Net.NetworkCredential(myMail.From.ToString(), password)
s.EnableSsl = True
s.Send(myMail)
End Using
End Using
End Sub
End Class
Usage C#:
{
Email em = new Email();
em.NewHeadlessEmail("myemail#gmail.com", "password", "recipient#email.com", "Subject Text", "Body Text");
}
Usage VB:
Dim em As New Email
em.NewHeadlessEmail("myemail#gmail.com", "password", "recipient#email.com", "Subject Text", "Body Text")
Use Port number 587
With the following code, it will work successfully.
MailMessage mail = new MailMessage();
mail.From = new MailAddress("abc#mydomain.com", "Enquiry");
mail.To.Add("abcdef#yahoo.com");
mail.IsBodyHtml = true;
mail.Subject = "Registration";
mail.Body = "Some Text";
mail.Priority = MailPriority.High;
SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
//smtp.UseDefaultCredentials = true;
smtp.Credentials = new System.Net.NetworkCredential("xyz#gmail.com", "<my gmail pwd>");
smtp.EnableSsl = true;
//smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.Send(mail);
But, there is a problem with using gmail. The email will be sent successfully, but the recipient inbox will have the gmail address in the 'from address' instead of the 'from address' mentioned in the code.
To solve this, please follow the steps mentioned at the following link.
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
ActiveUp.Net.Mail.SmtpMessage smtpmsg = new ActiveUp.Net.Mail.SmtpMessage();
smtpmsg.From.Email = "abcd#test.com";
smtpmsg.To.Add(To);
smtpmsg.Bcc.Add("vijay#indiagreat.com");
smtpmsg.Subject = Subject;
smtpmsg.BodyText.Text = Body;
smtpmsg.Send("mail.test.com", "abcd#sss.com", "user#1234", ActiveUp.Net.Mail.SaslMechanism.Login);
simple code works
MailMessage mail = new MailMessage();
mail.To.Add(to);
mail.From = new MailAddress(from);
mail.Subject = subject;
mail.Body = body;
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient("smtp.gmail.com",587);
smtp.EnableSsl = true;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new System.Net.NetworkCredential(address, password);
smtp.Send(mail);

Categories

Resources