Sending email in asp.net - asp.net

I want to send an email from my site's email "info#mysitename.com".
But there is an error and the email don't send.
here in my code and error :
public void SendMail(string Subject, string To, string Body)
{
SmtpClient MyMail = new SmtpClient();
MailMessage MyMsg = new MailMessage();
MyMail.Host = "info#sitename.com";
MyMsg.To.Add(new MailAddress(To));
MyMsg.Subject = Subject;
MyMsg.SubjectEncoding = Encoding.UTF8;
MyMsg.IsBodyHtml = true;
MyMsg.From = new MailAddress("info#sitename.com", "myname");
MyMsg.BodyEncoding = Encoding.UTF8;
MyMsg.Body = Body;
MyMail.UseDefaultCredentials = false;
NetworkCredential MyCredentials = new NetworkCredential("info#sitename", "pass");
MyMail.Credentials = MyCredentials;
MyMail.Send(MyMsg);
}
This is the error:

You are misunderstanding what the SmtpClient Host property is used for.
This line of code here is wrong...
MyMail.Host = "info#sitename.com";
MyMail.Host should point to your SMTP server - you're trying to set it to the FROM address.
You are already setting the FROM address in your MailMessage object, int he line shown below...
MyMsg.From = new MailAddress("info#sitename.com", "myname");
So, just to give you an example, I might have a server at the IP 10.1.0.5 and it runs an SMTP server on port 25. You would set your MyMail.Host = "10.1.0.5", or even better just set it in the constructor like this...
SmtpClient MyMail = new SmtpClient("10.1.0.5", 25);
Now, this is just an example - I don't know if / where you might have an SMTP server set up. But if you don't have an SMTP server set up, that's something you're missing. If you do have it set up, the Host property should be its IP or domain name.

Related

How to send email from an asp.net application using gmail smtp [duplicate]

Instead of relying on my host to send an email, I was thinking of sending the email messages using my Gmail account. The emails are personalized emails to the bands I play on my show.
Is it possible to do it?
Be sure to use System.Net.Mail, not the deprecated System.Web.Mail. Doing SSL with System.Web.Mail is a gross mess of hacky extensions.
using System.Net;
using System.Net.Mail;
var fromAddress = new MailAddress("from#gmail.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(fromAddress.Address, fromPassword)
};
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body
})
{
smtp.Send(message);
}
Additionally go to the Google Account > Security page and look at the Signing in to Google > 2-Step Verification setting.
If it is enabled, then you have to generate a password allowing .NET to bypass the 2-Step Verification. To do this, click on Signing in to Google > App passwords, select app = Mail, and device = Windows Computer, and finally generate the password. Use the generated password in the fromPassword constant instead of your standard Gmail password.
If it is disabled, then you have to turn on Less secure app access, which is not recommended! So better enable the 2-Step verification.
The above answer doesn't work. You have to set DeliveryMethod = SmtpDeliveryMethod.Network or it will come back with a "client was not authenticated" error. Also it's always a good idea to put a timeout.
Revised code:
using System.Net.Mail;
using System.Net;
var fromAddress = new MailAddress("from#gmail.com", "From Name");
var toAddress = new MailAddress("to#yahoo.com", "To Name");
const string fromPassword = "password";
const string subject = "test";
const string body = "Hey now!!";
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
Credentials = new NetworkCredential(fromAddress.Address, fromPassword),
Timeout = 20000
};
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body
})
{
smtp.Send(message);
}
Edit 2022
Starting May 30, 2022, ​​Google will no longer support the use of third-party apps or devices which ask you to sign in to your Google Account using only your username and password.
But you still can send E-Mail via your gmail account.
Go to https://myaccount.google.com/security and turn on two step verification. Confirm your account by phone if needed.
Click "App Passwords", just below the "2 step verification" tick.
Request a new password for the mail app.
Now just use this password instead of the original one for you account!
public static void SendMail2Step(string SMTPServer, int SMTP_Port, string From, string Password, string To, string Subject, string Body, string[] FileNames) {
var smtpClient = new SmtpClient(SMTPServer, SMTP_Port) {
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
EnableSsl = true
};
smtpClient.Credentials = new NetworkCredential(From, Password); //Use the new password, generated from google!
var message = new System.Net.Mail.MailMessage(new System.Net.Mail.MailAddress(From, "SendMail2Step"), new System.Net.Mail.MailAddress(To, To));
smtpClient.Send(message);
}
Use like this:
SendMail2Step("smtp.gmail.com", 587, "youraccount#gmail.com",
"yjkjcipfdfkytgqv",//This will be generated by google, copy it here.
"recipient#barcodes.bg", "test message subject", "Test message body ...", null);
For the other answers to work "from a server" first Turn On Access for less secure apps in the gmail account. This will be deprecated 30 May 2022
Looks like recently google changed it's security policy. The top rated answer no longer works, until you change your account settings as described here: https://support.google.com/accounts/answer/6010255?hl=en-GB
As of March 2016, google changed the setting location again!
This is to send email with attachement.. Simple and short..
source: http://coding-issues.blogspot.in/2012/11/sending-email-with-attachments-from-c.html
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("your mail#gmail.com");
mail.To.Add("to_mail#gmail.com");
mail.Subject = "Test Mail - 1";
mail.Body = "mail with attachment";
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment("c:/textfile.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);
}
Google may block sign in attempts from some apps or devices that do not use modern security standards. Since these apps and devices are easier to break into, blocking them helps keep your account safer.
Some examples of apps that do not support the latest security standards include:
The Mail app on your iPhone or iPad with iOS 6 or below
The Mail app on your Windows phone preceding the 8.1 release
Some Desktop mail clients like Microsoft Outlook and Mozilla Thunderbird
Therefore, you have to enable Less Secure Sign-In in your google account.
After sign into google account, go to:
https://myaccount.google.com/lesssecureapps
or
https://www.google.com/settings/security/lesssecureapps
In C#, you can use the following code:
using (MailMessage mail = new MailMessage())
{
mail.From = new MailAddress("email#gmail.com");
mail.To.Add("somebody#domain.com");
mail.Subject = "Hello World";
mail.Body = "<h1>Hello</h1>";
mail.IsBodyHtml = true;
mail.Attachments.Add(new Attachment("C:\\file.zip"));
using (SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587))
{
smtp.Credentials = new NetworkCredential("email#gmail.com", "password");
smtp.EnableSsl = true;
smtp.Send(mail);
}
}
For me to get it to work, i had to enable my gmail account making it possible for other apps to gain access. This is done with the "enable less secure apps" and also using this link:
https://accounts.google.com/b/0/DisplayUnlockCaptcha
Here is my version: "Send Email In C # Using Gmail".
using System;
using System.Net;
using System.Net.Mail;
namespace SendMailViaGmail
{
class Program
{
static void Main(string[] args)
{
//Specify senders gmail address
string SendersAddress = "Sendersaddress#gmail.com";
//Specify The Address You want to sent Email To(can be any valid email address)
string ReceiversAddress = "ReceiversAddress#yahoo.com";
//Specify The password of gmial account u are using to sent mail(pw of sender#gmail.com)
const string SendersPassword = "Password";
//Write the subject of ur mail
const string subject = "Testing";
//Write the contents of your mail
const string body = "Hi This Is my Mail From Gmail";
try
{
//we will use Smtp client which allows us to send email using SMTP Protocol
//i have specified the properties of SmtpClient smtp within{}
//gmails smtp server name is smtp.gmail.com and port number is 587
SmtpClient smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
Credentials = new NetworkCredential(SendersAddress, SendersPassword),
Timeout = 3000
};
//MailMessage represents a mail message
//it is 4 parameters(From,TO,subject,body)
MailMessage message = new MailMessage(SendersAddress, ReceiversAddress, subject, body);
/*WE use smtp sever we specified above to send the message(MailMessage message)*/
smtp.Send(message);
Console.WriteLine("Message Sent Successfully");
Console.ReadKey();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadKey();
}
}
}
}
I hope this code will work fine. You can have a try.
// Include this.
using System.Net.Mail;
string fromAddress = "xyz#gmail.com";
string mailPassword = "*****"; // Mail id password from where mail will be sent.
string messageBody = "Write the body of the message here.";
// Create smtp connection.
SmtpClient client = new SmtpClient();
client.Port = 587;//outgoing port for the mail.
client.Host = "smtp.gmail.com";
client.EnableSsl = true;
client.Timeout = 10000;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential(fromAddress, mailPassword);
// Fill the mail form.
var send_mail = new MailMessage();
send_mail.IsBodyHtml = true;
//address from where mail will be sent.
send_mail.From = new MailAddress("from#gmail.com");
//address to which mail will be sent.
send_mail.To.Add(new MailAddress("to#example.com");
//subject of the mail.
send_mail.Subject = "put any subject here";
send_mail.Body = messageBody;
client.Send(send_mail);
Source : Send email in ASP.NET C#
Below is a sample working code for sending in a mail using C#, in the below example I am using google’s smtp server.
The code is pretty self explanatory, replace email and password with your email and password values.
public void SendEmail(string address, string subject, string message)
{
string email = "yrshaikh.mail#gmail.com";
string password = "put-your-GMAIL-password-here";
var loginInfo = new NetworkCredential(email, password);
var msg = new MailMessage();
var smtpClient = new SmtpClient("smtp.gmail.com", 587);
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);
}
To avoid security issues in Gmail, you should generate an app password first from your Gmail settings and you can use this password instead of a real password to send an email even if you use two steps verification.
Include this,
using System.Net.Mail;
And then,
MailMessage sendmsg = new MailMessage(SendersAddress, ReceiversAddress, subject, body);
SmtpClient client = new SmtpClient("smtp.gmail.com");
client.Port = 587;
client.Credentials = new System.Net.NetworkCredential("mail-id#gmail.com","password");
client.EnableSsl = true;
client.Send(sendmsg);
If you want to send background email, then please do the below
public void SendEmail(string address, string subject, string message)
{
Thread threadSendMails;
threadSendMails = new Thread(delegate()
{
//Place your Code here
});
threadSendMails.IsBackground = true;
threadSendMails.Start();
}
and add namespace
using System.Threading;
Try This,
private void button1_Click(object sender, EventArgs e)
{
try
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("your_email_address#gmail.com");
mail.To.Add("to_address");
mail.Subject = "Test Mail";
mail.Body = "This is for testing SMTP mail from GMAIL";
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("username", "password");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
MessageBox.Show("mail Send");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
use this way
MailMessage sendmsg = new MailMessage(SendersAddress, ReceiversAddress, subject, body);
SmtpClient client = new SmtpClient("smtp.gmail.com");
client.Port = Convert.ToInt32("587");
client.EnableSsl = true;
client.Credentials = new System.Net.NetworkCredential("mail-id#gmail.com","MyPassWord");
client.Send(sendmsg);
Don't forget this :
using System.Net;
using System.Net.Mail;
From 1 Jun 2022, ​​Google has added some security features
Google is no longer support the use of third-party apps or devices which ask you to sign in to your Google Account using only your username and password or send mail directly using username and password of google account. But you still can send E-Mail via your gmail account using generating app password.
Below are the steps for generate new password.
Go to https://myaccount.google.com/security
Turn on two step verification.
Confirm your account by phone if needed.
Click "App Passwords", just below the "2 step verification" tick. Request a new password for the mail app.
Now we have to use this password for sending mail instead of the original password of your account.
Below is the example code for sending mail
public static void SendMailFromApp(string SMTPServer, int SMTP_Port, string From, string Password, string To, string Subject, string Body) {
var smtpClient = new SmtpClient(SMTPServer, SMTP_Port) {
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
EnableSsl = true
};
smtpClient.Credentials = new NetworkCredential(From, Password); //Use the new password, generated from google!
var message = new System.Net.Mail.MailMessage(new System.Net.Mail.MailAddress(From, "SendMail2Step"), new System.Net.Mail.MailAddress(To, To));
smtpClient.Send(message);
}
You can to call method like below
SendMailFromApp("smtp.gmail.com", 25, "mygmailaccount#gmail.com",
"tyugyyj1556jhghg",//This will be generated by google, copy it here.
"mailme#gmail.com", "New Mail Subject", "Body of mail from My App");
Changing sender on Gmail / Outlook.com email:
To prevent spoofing - Gmail/Outlook.com won't let you send from an arbitrary user account name.
If you have a limited number of senders you can follow these instructions and then set the From field to this address: Sending mail from a different address
If you are wanting to send from an arbitrary email address (such as a feedback form on website where the user enters their email and you don't want them emailing you directly) about the best you can do is this :
msg.ReplyToList.Add(new System.Net.Mail.MailAddress(email, friendlyName));
This would let you just hit 'reply' in your email account to reply to the fan of your band on a feedback page, but they wouldn't get your actual email which would likely lead to a tonne of spam.
If you're in a controlled environment this works great, but please note that I've seen some email clients send to the from address even when reply-to is specified (I don't know which).
I had the same issue, but it was resolved by going to gmail's security settings and Allowing Less Secure apps.
The Code from Domenic & Donny works, but only if you enabled that setting
If you are signed in (to Google) you can follow this link and toggle "Turn on" for "Access for less secure apps"
using System;
using System.Net;
using System.Net.Mail;
namespace SendMailViaGmail
{
class Program
{
static void Main(string[] args)
{
//Specify senders gmail address
string SendersAddress = "Sendersaddress#gmail.com";
//Specify The Address You want to sent Email To(can be any valid email address)
string ReceiversAddress = "ReceiversAddress#yahoo.com";
//Specify The password of gmial account u are using to sent mail(pw of sender#gmail.com)
const string SendersPassword = "Password";
//Write the subject of ur mail
const string subject = "Testing";
//Write the contents of your mail
const string body = "Hi This Is my Mail From Gmail";
try
{
//we will use Smtp client which allows us to send email using SMTP Protocol
//i have specified the properties of SmtpClient smtp within{}
//gmails smtp server name is smtp.gmail.com and port number is 587
SmtpClient smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
Credentials = new NetworkCredential(SendersAddress, SendersPassword),
Timeout = 3000
};
//MailMessage represents a mail message
//it is 4 parameters(From,TO,subject,body)
MailMessage message = new MailMessage(SendersAddress, ReceiversAddress, subject, body);
/*WE use smtp sever we specified above to send the message(MailMessage message)*/
smtp.Send(message);
Console.WriteLine("Message Sent Successfully");
Console.ReadKey();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadKey();
}
}
}
}
Google has removed the less secure apps setting from our Google accounts, this means that we can no longer send emails from the SMTP server using our actual google passwords. We need to either use Xoauth2 and authorize the user or create a an apps password on an account that has 2fa enabled.
Once created an apps password can be used in place of your standard gmail password.
class Program
{
private const string To = "test#test.com";
private const string From = "test#test.com";
private const string GoogleAppPassword = "XXXXXXXX";
private const string Subject = "Test email";
private const string Body = "<h1>Hello</h1>";
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
var smtpClient = new SmtpClient("smtp.gmail.com")
{
Port = 587,
Credentials = new NetworkCredential(From , GoogleAppPassword),
EnableSsl = true,
};
var mailMessage = new MailMessage
{
From = new MailAddress(From),
Subject = Subject,
Body = Body,
IsBodyHtml = true,
};
mailMessage.To.Add(To);
smtpClient.Send(mailMessage);
}
}
Quick fix for SMTP username and password not accepted error
After google update, This is the valid method to send an email using c# or .net.
using System;
using System.Net;
using System.Net.Mail;
namespace EmailApp
{
internal class Program
{
public static void Main(string[] args)
{
String SendMailFrom = "Sender Email";
String SendMailTo = "Reciever Email";
String SendMailSubject = "Email Subject";
String SendMailBody = "Email Body";
try
{
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com",587);
SmtpServer.DeliveryMethod = SmtpDeliveryMethod.Network;
MailMessage email = new MailMessage();
// START
email.From = new MailAddress(SendMailFrom);
email.To.Add(SendMailTo);
email.CC.Add(SendMailFrom);
email.Subject = SendMailSubject;
email.Body = SendMailBody;
//END
SmtpServer.Timeout = 5000;
SmtpServer.EnableSsl = true;
SmtpServer.UseDefaultCredentials = false;
SmtpServer.Credentials = new NetworkCredential(SendMailFrom, "Google App Password");
SmtpServer.Send(email);
Console.WriteLine("Email Successfully Sent");
Console.ReadKey();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
Console.ReadKey();
}
}
}
}
For creating the app password, you can follow this article:
https://www.techaeblogs.live/2022/06/how-to-send-email-using-gmail.html
Here is one method to send mail and getting credentials from web.config:
public static string SendEmail(string To, string Subject, string Msg, bool bodyHtml = false, bool test = false, Stream AttachmentStream = null, string AttachmentType = null, string AttachmentFileName = null)
{
try
{
System.Net.Mail.MailMessage newMsg = new System.Net.Mail.MailMessage(System.Configuration.ConfigurationManager.AppSettings["mailCfg"], To, Subject, Msg);
newMsg.BodyEncoding = System.Text.Encoding.UTF8;
newMsg.HeadersEncoding = System.Text.Encoding.UTF8;
newMsg.SubjectEncoding = System.Text.Encoding.UTF8;
System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient();
if (AttachmentStream != null && AttachmentType != null && AttachmentFileName != null)
{
System.Net.Mail.Attachment attachment = new System.Net.Mail.Attachment(AttachmentStream, AttachmentFileName);
System.Net.Mime.ContentDisposition disposition = attachment.ContentDisposition;
disposition.FileName = AttachmentFileName;
disposition.DispositionType = System.Net.Mime.DispositionTypeNames.Attachment;
newMsg.Attachments.Add(attachment);
}
if (test)
{
smtpClient.PickupDirectoryLocation = "C:\\TestEmail";
smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.SpecifiedPickupDirectory;
}
else
{
//smtpClient.EnableSsl = true;
}
newMsg.IsBodyHtml = bodyHtml;
smtpClient.Send(newMsg);
return SENT_OK;
}
catch (Exception ex)
{
return "Error: " + ex.Message
+ "<br/><br/>Inner Exception: "
+ ex.InnerException;
}
}
And the corresponding section in web.config:
<appSettings>
<add key="mailCfg" value="yourmail#example.com"/>
</appSettings>
<system.net>
<mailSettings>
<smtp deliveryMethod="Network" from="yourmail#example.com">
<network defaultCredentials="false" host="mail.exapmple.com" userName="yourmail#example.com" password="your_password" port="25"/>
</smtp>
</mailSettings>
</system.net>
Try this one
public static bool Send(string receiverEmail, string ReceiverName, string subject, string body)
{
MailMessage mailMessage = new MailMessage();
MailAddress mailAddress = new MailAddress("abc#gmail.com", "Sender Name"); // abc#gmail.com = input Sender Email Address
mailMessage.From = mailAddress;
mailAddress = new MailAddress(receiverEmail, ReceiverName);
mailMessage.To.Add(mailAddress);
mailMessage.Subject = subject;
mailMessage.Body = body;
mailMessage.IsBodyHtml = true;
SmtpClient mailSender = new SmtpClient("smtp.gmail.com", 587)
{
EnableSsl = true,
UseDefaultCredentials = false,
DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network,
Credentials = new NetworkCredential("abc#gmail.com", "pass") // abc#gmail.com = input sender email address
//pass = sender email password
};
try
{
mailSender.Send(mailMessage);
return true;
}
catch (SmtpFailedRecipientException ex)
{
// Write the exception to a Log file.
}
catch (SmtpException ex)
{
// Write the exception to a Log file.
}
finally
{
mailSender = null;
mailMessage.Dispose();
}
return false;
}
You can try Mailkit. It gives you better and advance functionality for send mail. You can find more from this Here is an example
MimeMessage message = new MimeMessage();
message.From.Add(new MailboxAddress("FromName", "YOU_FROM_ADDRESS#gmail.com"));
message.To.Add(new MailboxAddress("ToName", "YOU_TO_ADDRESS#gmail.com"));
message.Subject = "MyEmailSubject";
message.Body = new TextPart("plain")
{
Text = #"MyEmailBodyOnlyTextPart"
};
using (var client = new SmtpClient())
{
client.Connect("SERVER", 25); // 25 is port you can change accordingly
// Note: since we don't have an OAuth2 token, disable
// the XOAUTH2 authentication mechanism.
client.AuthenticationMechanisms.Remove("XOAUTH2");
// Note: only needed if the SMTP server requires authentication
client.Authenticate("YOUR_USER_NAME", "YOUR_PASSWORD");
client.Send(message);
client.Disconnect(true);
}
Copying from another answer, the above methods work but gmail always replaces the "from" and "reply to" email with the actual sending gmail account. apparently there is a work around however:
http://karmic-development.blogspot.in/2013/10/send-email-from-aspnet-using-gmail-as.html
"3. In the Accounts Tab, Click on the link "Add another email address you own" then verify it"
Or possibly this
Update 3: Reader Derek Bennett says, "The solution is to go into your gmail Settings:Accounts and "Make default" an account other than your gmail account. This will cause gmail to re-write the From field with whatever the default account's email address is."
This is no longer supported incase you are trying to do this now.
https://support.google.com/accounts/answer/6010255?hl=en&visit_id=637960864118404117-800836189&p=less-secure-apps&rd=1#zippy=
If your Google password doesn't work, you may need to create an app-specific password for Gmail on Google.
https://support.google.com/accounts/answer/185833?hl=en

Server does not support secure connections in C#

I'm getting the error "Server does not support secure connections" with my code below.
SmtpClient smtp = new SmtpClient();
MailMessage mail = new MailMessage();
mail.From = new MailAddress("*****#gmail.com");
mail.To.Add(recieverId);
mail.Subject = "Invoice Copy and Delivery Confirmation for booksap.com Order " + orderno + ". Please Share Feedback.";
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment(Server.MapPath("OrderMail\\Invoice.pdf"));
mail.Attachments.Add(attachment);
MailBody = "We are pleased to inform that the following items in your order " + orderno + " have been placed. This completes your order. Thank you for shopping! ";
StreamReader reader = new StreamReader(Server.MapPath("~/MailHTMLPage.htm"));
string readFile = reader.ReadToEnd();
string myString = "";
myString = readFile;
myString = myString.Replace("$$Name$$", ContactPersonName);
myString = myString.Replace("$$MailBody$$", MailBody);
mail.Body = myString.ToString();
mail.IsBodyHtml = true;
mail.Priority = MailPriority.High;
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
smtp.UseDefaultCredentials = true;
smtp.Port = 587;
smtp.Credentials = new System.Net.NetworkCredential("*******#gmail.com", "*******");
smtp.Send(mail);
mail.Dispose();
mail = null;
How can I fix this issue?
If I set
EnabledSsl = false
it will return the error: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.1 Client was not authenticated.
That error message is typically caused by one of the following:
Incorrect connection settings, such as the wrong port specified for
the secured or non-secured connection
Incorrect credentials. I would verify the username and password
combination, to make sure the credentials are correct.
if it is ok,I think you have to set DeliveryMethod = SmtpDeliveryMethod.Network
simply try this..
using System.Net;
using System.Net.Mail;
var fromAddress = new MailAddress("from#gmail.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(fromAddress.Address, fromPassword)
};
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body
})
{
smtp.Send(message);
}
ALSO
Change account access for less secure apps
Go to the "Less secure apps" section in My Account.
Try Option 2:
#Abhishek Yes.The code that you have written will send the message to the server just check your mail box (***#gmail.com) but smtp client of google is preventing you from entering into thier domain.
You have to make your gmail less secure that is you need to allow sign in attempt.
Check Your mail box,you should have such response from gmail domain and you need to make your account less secure.
I think its about captcha and bots preventing such logging in,people who know can throw some light in these things.Make your account less suspicious.Hope this helps
If you are working in any specific domain(company) then might be the company have personal proxy authentication so you will have to bypass proxy authentication for prevent error.
first you need to add
smtpServer.EnableSsl = false;
then add below code in your web.config
<system.net>
<defaultProxy enabled="true" useDefaultCredentials="true">
<proxy usesystemdefault="True" bypassonlocal="True" />
</defaultProxy>
</system.net>

Sending an email with ASP .Net and Gmail SMTP

I am developping an ASP .Net website.
One of my ASPX page contains a button.
When this button is clicked I want to send an email by using the Gmail SMTP server.
I want to use my Gmail account as credentials.
Here is the button's click event handler :
protected void m_myButton_Click(object p_sender, EventArgs p_args)
{
string l_subject = "My subject";
StringBuilder l_builder = new StringBuilder();
// ...
string l_body = l_builder.ToString();
string l_host = ConfigurationManager.AppSettings["SmtpHost"];
int l_port = int.Parse(ConfigurationManager.AppSettings["SmtpPort"]);
NameValueCollection l_smtpAccount = (NameValueCollection)ConfigurationManager.GetSection("smtpAccount");
string l_address = l_smtpAccount["SmtpAddress"];
string l_password = l_smtpAccount["SmtpPassword"];
MailMessage l_mail = new MailMessage();
l_mail.From = new MailAddress(l_address);
l_mail.To.Add(l_address);
l_mail.Subject = l_subject;
l_mail.Body = l_body;
SmtpClient l_smtp = new SmtpClient();
l_smtp.Host = l_host; // l_host = "smtp.gmail.com"
l_smtp.Port = l_port; // l_port = 587
l_smtp.EnableSsl = true;
l_smtp.UseDefaultCredentials = false;
l_smtp.Credentials = new NetworkCredential(l_address, l_password);
l_smtp.Send(l_mail);
}
The command line l_smtp.Send(l_mail) fails.
A SMTP exception is raised and the InnerException property informs me that (translation from French to English) : No connection has been etablished because the target computer has refused it 173.194.67.108:587
My code is based on code found on this page : http://www.codeproject.com/Questions/254743/sending-email-in-asp-net-using-smtp-gmail-server
Any help will be greatly appreciated
Try this...
protected void Button1_Click(object sender, EventArgs e)
{
MailMessage mail = new MailMessage();
mail.To.Add("Email ID where email is to be send");
mail.To.Add("Another Email ID where you wanna send same email");
mail.From = new MailAddress("YourGmailID#gmail.com");
mail.Subject = "Email using Gmail";
string Body = "Hi, this mail is to test sending mail"+
"using Gmail in ASP.NET";
mail.Body = Body;
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com"; //Or Your SMTP Server Address
smtp.Credentials = new System.Net.NetworkCredential
("YourUserName#gmail.com","YourGmailPassword");
//Or your Smtp Email ID and Password
smtp.EnableSsl = true;
smtp.Send(mail);
}
No connection has been etablished because the target computer has refused it 73.194.67.108:587
Try the other SMTP port: 465
I have turned my antivirus program off as advised by Rup and I have not got any exception.
I will created a custom rule in my antivirus program to allow communication between my ASP .Net website and the Gmail SMTP server.

How Can i Send Mail Through Exchange Server by using SMTP

I want to Run Below code without
NetworkCredential nc = new Net.NetworkCredential("USERNAME", "PASSWORD").
BY using Only Exchange Host (Server Name) And Port
Im Getting Error For this code : Mailbox unavailable. The server response was: 5.7.1 Client does not have permissions to send as this sender
protected void SendEmail(object sender, EventArgs e)
{
SmtpClient smtpClient = new SmtpClient("ExchangeServerName",25);
MailMessage message = new MailMessage();
try
{
MailAddress fromAddress = new MailAddress("bala#OfficeName.com", "From Me");
MailAddress toAddress = new MailAddress("bala#OfficeName.com", "To You");
message.From = fromAddress;
message.To.Add(toAddress);
message.Subject = "Testing!";
message.Body = "This is the body of a sample message";
smtpClient.UseDefaultCredentials = true;
System.Net.NetworkCredential nc = CredentialCache.DefaultNetworkCredentials;
smtpClient.Credentials = (System.Net.ICredentialsByHost)nc.GetCredential("ExchangeServerName", 25, "Basic");
smtpClient.Send(message);
lblText.Text ="Email sent.";
}
catch (Exception ex)
{
lblText.Text = "Coudn't send the message!\n " + ex.Message;
}
}
I have done it. For more details about my code use this link.
Below Code is worked Fine with
Server : Windows Server 2003,Windows Server 2008,Windows Server 2008 R2
IIS : 6.0, 7.0
.Net Frame Wotk : 2.0,3.5,4.0
string sMessage;
SmtpClient smtpClient = new SmtpClient();
MailMessage message = new MailMessage();
try
{
//you can provide invalid from address. but to address Should be valil
MailAddress fromAddress = new MailAddress("bala#technospine.com", "BALA");
smtpClient.Host = "Exchange Server Name";
smtpClient.Port = 25;
//smtpClient.Port = 587;
smtpClient.UseDefaultCredentials = true;
message.From = fromAddress;
message.To.Add(bala#technospine.com); //Recipent email
message.Subject = _subject;
message.Body = _details;
message.IsBodyHtml = true;
//smtpClient.EnableSsl = true;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.Send(message);
sMessage = "Email sent.";
}
catch (Exception ex)
{
sMessage = "Coudn't send the message!\n " + ex.Message;
}
lblMailStatus.Text = sMessage;
You are attempting to send a mail message using Exchange. In order to do that, the sender (or sending process) must have permissions on the account it is logged in under to send on behalf of the user you are specifying as the sender. This is different from going through Exchange's SMTP mail transfer agent (MTA) in order to have Exchange receive and route an email message. So you are on the right track with knowing you should do this using SMTP, but you are just trying to use the wrong API for accomplishing this. You want to take a look at CDOSYS for sending it through the SMTP MTA without having to do user authentication. Search on System.Web.Mail.MailMessage for more specific examples - there are plenty out there. If the Exchange server does not seem to accept/deliver the SMTP message delivered to it in this fashion, you might simply need to open up its configuration a bit. In that event, the Exchange server is probably configured with tight security on routing of mail received via its SMTP MTA and just needs to have the IP address of the machine(s) you are sending these messages from configured to allow for mail forwarding.
try NetworkCredential nc = new Net.NetworkCredential("USERNAME", "PASSWORD","DOMAIN")

Sending e-mail in ASP .Net

How to send e-mail on ASP .Net using outlook address??
I've tried this code but no luck:
Dim mailMessage As System.Net.Mail.MailMessage = New System.Net.Mail.MailMessage()
mailMessage.From = New System.Net.Mail.MailAddress("fromAddress")
mailMessage.To.Add(New System.Net.Mail.MailAddress("toAddress"))
mailMessage.Priority = Net.Mail.MailPriority.High
mailMessage.Subject = "Subject"
mailMessage.Body = "test"
Dim smtpClient As System.Net.Mail.SmtpClient = New System.Net.Mail.SmtpClient("xxx.outlook.com", portNumber)
smtpClient.Send(mailMessage) //--> got error here
But while I'm execute the code, it got this error message:
The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.1 Client was not authenticated
I've tried to add a line of code:
smtpClient.Credentials = New System.Net.NetworkCredential(username, password)
But still can't send the e-mail.
Anyone can help?
Try smtpClient.UseDefaultCredentials = false; before you set new Credentials
Try to set smtpClient.EnableSsl to true / false depending on your environment
I'm guessing you are using Exchange 2007 or later as backend?
Anyway, your mail server does not allow you to send mails anonymously. You'll either need to supply a username/password in your code or allow unauthenticated relaying from your webserver.
Talk to your IT guys what they prefer.
I did it using c#.This may help you.Please check.
MailMessage msg1 = new MailMessage();
msg1.From = strEFrom;
msg1.To = strETo;
msg1.Cc = strECC;
msg1.Subject = "Hi";
msg1.Priority = MailPriority.High;
msg1.BodyFormat = MailFormat.Html;
msg1.Body = strBody;
SmtpMail.SmtpServer = ConfigurationSettings.AppSettings["MailServer"].ToString();
SmtpMail.Send(msg1);
and in web.config file
<appSettings>
<add key="MailServer" value=""/>
</appSettings>
Try these settings check for .EnableSSL property to true/false and the smtp post number on which your mail server listen for outgoing mail.
When you do not set enable the SSL settings in outlook for gmail outlook configuration then it gives same error but the reason was found the SSL settings..
well try this may it will solve your problem..
msg.IsBodyHtml = true;
msg.Body = mailContent;
SmtpClient mailClient = new SmtpClient("smtp.mail.yahoo.com", 25);
NetworkCredential NetCrd = new NetworkCredential(frmyahoo, frmpwd);
mailClient.UseDefaultCredentials = false;
mailClient.Credentials = NetCrd;
mailClient.EnableSsl = false;
mailClient.DeliveryMethod = SmtpDeliveryMethod.Network;
mailClient.Send(msg);
if it does not solve your problem then check your mail server/ client for the problem.
public static bool SendMail(string mailAccount, string password, string to, string subject, string message)
{
try
{
NetworkCredential loginInfo = new NetworkCredential(mailAccount, password);
MailMessage msg = new MailMessage();
msg.From = new MailAddress(from);
msg.To.Add(new MailAddress(to));
msg.Subject = subject;
msg.Body = message;
msg.IsBodyHtml = false;
SmtpClient client = new SmtpClient("smtp.gmail.com");
client.EnableSsl = true;
client.UseDefaultCredentials = false;
client.Credentials = loginInfo;
client.Send(msg);
return true;
}
catch (Exception)
{
return false;
}
}
I use this code to send mail from my gmail account.
was having the same error, moved the client.UseDefaultCredentials = false; before setting client.Credentials and everything works.

Resources