How to use gmail SMTP in ASP.NET form - asp.net

I am a ASP novice and am troubleshooting a form for work. None of us here are ASP experts as we use PHP. But I am on the bottom of PHP experience as well, mostly working with HTML/CSS alone. My current forms credentials look like:
rotected Sub SubmitForm_Click(ByVal sender As Object, ByVal e As System.EventArgs)
If Not Page.IsValid Then Exit Sub
Dim SendResultsTo As String = "email to"
Dim smtpMailServer As String = "email server"
Dim smtpUsername As String = "email username"
Dim smtpPassword As String = "password"
Dim MailSubject As String = "Form Results"
How would I go about making this form send to a Gmail address? I know I must include the port (587) somewhere, but cannot figure out where, as this form doesn't match the syntax of any other forms I have seen. Any help would be greatly appreciated!

You can add this in your web.config file
<system.net>
<mailSettings>
<smtp from="yourMailId#gmail.com ">
<network host="smtp.gmail.com" defaultCredentials="false"
port="587" userName ="yourmail#gmail.com" password="yourpassword" />
</smtp>
</mailSettings>
</system.net>

protected void SendMail()
{
MailMessage msg = new MailMessage();
System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient();
try
{
msg.Subject = "Add Subject";
msg.Body = "Add Email Body Part";
msg.From = new MailAddress("Valid Email Address");
msg.To.Add("Valid Email Address");
msg.IsBodyHtml = true;
client.Host = "smtp.gmail.com";
System.Net.NetworkCredential basicauthenticationinfo = new System.Net.NetworkCredential("Valid Email Address", "Password");
client.Port = int.Parse("587");
client.EnableSsl = true;
client.UseDefaultCredentials = false;
client.Credentials = basicauthenticationinfo;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.Send(msg);
}
catch (Exception ex)
{
log.Error(ex.Message);
}
}

Create a System.Net.Mail.SmtpClient object, set the SMTP server info you are using.
Then create a System.Smtl.MailMessage with the message data and send it:
using (System.Net.Mail.SmtpClient mail = new System.Net.Mail.SmtpClient()) {
using (System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage("from*where.com", "to#where.com") {
IsBodyHtml = true,
Subject = "Subject text",
Body = messageBody,
}) {
mail.Send(message);
} // using
You can configure your SmtpClient in the constructor, we use web.comfig, so I don't have that code.

Google now blocks sign-ins from an app (even over SSL) to send an email. You have two options:
Enable less-secure apps for the account you are using; OR
Generate an app-password from Google (recommended)
For option 2, you will have to enable 2-factor authentication before you can generate an app pasword.
Here are the steps I took to get this working on my ASP.NET web app
How to configure an ASP.NET web app with Gmail SMTP

Try this.
Dim client As New Net.Mail.SmtpClient
client.UseDefaultCredentials = False
client.Credentials = New System.Net.NetworkCredential("sender#gmail.com", "password")
client.Host = "smtp.gmail.com"
client.Port = 587
client.EnableSsl = True
client.Send("sender#gmail.com","reciever#gmail.com","subject","body")

If you're using 2-step verification, don't forget to generate an application specific password and use that, not the password you use to log on to Gmail.
(Sorry I can't add this as a comment. Not enough rep at the time of posting this.)

There's no shortage of tutorials on how to send an email from within .NET.
Essentially you want a System.Net.Mail.SmtpClient object to interact with the SMTP server, a System.Net.Mail.MailMessage object to hold the message data, and configuration data in your config file to direct the client on how/where to send the message.

Related

SmtpClient not working after setting up app password and 2-factor authentication enabled

My CreateUserWizard sends an email when I press a button. The email is send via app password as follows
Protected Sub NewUserWizard_SendingMail(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.MailMessageEventArgs) Handles NewUserWizard.SendingMail
'Get the UserId of the just-added user
Dim newUser As MembershipUser = Membership.GetUser(NewUserWizard.UserName)
Dim newUserId As Guid = CType(newUser.ProviderUserKey, Guid)
'some more code...
Dim obj As SecurePassword = New SecurePassword()
Dim google As GoogleOauth = New GoogleOauth()
' Replace <%VerificationUrl%> with the appropriate URL and querystring
e.Message.Body = e.Message.Body.Replace("<%VerificationUrl%>", fullUrl)
Select Case ConfigurationSettings.AppSettings("WhichSMTP")
Case "gmail"
'no need to do anything
Try
obj.SendViaGmail(e.Message.Subject, e.Message.Body, e.Message.To.ToString())
Catch ex As Exception
Response.Write("Error sending email " & ex.Message)
End Try
End Select
End Sub
Secure.vb
Public Function SendViaGmail(subject As String, body As String, recipients As String)
Dim fromEmail As String = ConfigurationSettings.AppSettings("ContactEmail")
Dim smtpClient As Mail.SmtpClient = New Mail.SmtpClient("smtp.gmail.com") With {
.Port = 587,
.DeliveryMethod = SmtpDeliveryMethod.Network,
.Credentials = New NetworkCredential(fromEmail, "APP_PWD"),
.EnableSsl = True
}
Dim mailMessage As MailMessage = New MailMessage With {
.From = New Mail.MailAddress(fromEmail),
.Subject = subject,
.Body = body,
.IsBodyHtml = True
}
mailMessage.[To].Add(recipients)
If smtpClient IsNot Nothing Then
smtpClient.Send(mailMessage)
End If
End Function
I keep getting smtp server requires a secure connection or the client was not authenticated,...
also, I actually receive the email after which it just crashed the application. I have setup 2-factor authentication on my gmail account, generated app password and tried everything given on this post including re-ordering of credentials etc..nothing works!!!
The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.0 Authentication Required.
UPDATE
I have also just found a setting in web.config (I have replaced this password with app password) - result is the same
<system.net>
<mailSettings>
<smtp deliveryMethod="Network" from="vl#gmail.com">
<network defaultCredentials="false" enableSsl="true" host="smtp.gmail.com" port="587" userName="vl#gmail.com" password="****" />
</smtp>
</mailSettings>
</system.net>
First remove .DeliveryMethod = SmtpDeliveryMethod.Network, from your code, then make sure that the From Email address is the email address of the user that the apps password matches.
I have tested this and it works.
Private Function SendViaGmail(subject As String, body As String, recipients As String) As String
Dim smtpClient As Mail.SmtpClient = New Mail.SmtpClient("smtp.gmail.com") With {
.Port = 587,
.Credentials = New NetworkCredential(FromEmail, GoogleAppPassword),
.EnableSsl = True
}
Dim mailMessage As MailMessage = New MailMessage With {
.From = New Mail.MailAddress(FromEmail),
.Subject = subject,
.Body = body,
.IsBodyHtml = True
}
mailMessage.[To].Add(recipients)
If smtpClient IsNot Nothing Then
smtpClient.Send(mailMessage)
Return "Message sent."
End If
Return "Error: failed to create smtpClient."
End Function

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>

Subscription Page in asp.net

I have a registration page I am sending an email from asp.net ,one mail to the registered user and other mail to the admin that too with different body...Ho can I achieve this? Also, User should give a confirmation link saying that you have subscribed and when the user clicks on the mail given link , a mail should fire to the admin saying that This User has been Registered.
http://www.webcodeexpert.com/2013/08/create-registration-form-and-send.html
You can use this link to achive the activation for user. But for sending mail to the admin, Use simple send email method.
Try this way, Send the from address and body details by yourself .
public void SendMail(string FromEmail, string Subject, string Body)
{
string ToEmail="YourAdmin#Gmail.com";
System.Net.Mail.MailMessage eMail = new System.Net.Mail.MailMessage();
eMail.From = new System.Net.Mail.MailAddress(FromEmail);
eMail.To.Add(ToEmail);
eMail.Subject = Subject;
eMail.IsBodyHtml = true;
eMail.Body = Body;
System.Net.Mail.SmtpClient SMTP = new System.Net.Mail.SmtpClient();
SMTP.Send(eMail);
eMail.Dispose();
}
Web.Config:
<system.net>
<mailSettings>
<smtp>
<network host="your stmp server" port="25" userName="your from email" password="your password"/>
</smtp>
</mailSettings>
</system.net>
Should be you have mail hosting server .
and if you want to send mail without page postback , See my little bit blog
These lines of code is used to send mail in aspx.cs page,make a try.if yo are using asp.net with c#
in aspx
<asp:CheckBox ID="CheckBoxMark1" runat="server" />
CheckBox Ckbox = (CheckBox)row.FindControl("CheckBoxMark1");
if (Ckbox.Checked == true)
{
sendMail(toemail);
//other code
}
public void sendMail(String toemail)
{
MailMessage mail = new MailMessage();
mail.To.Add(toemail);
mail.From = new MailAddress("sender#gmail.com");
mail.Subject = "Subject";
mail.Body = " Your Contents in the mail";
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new System.Net.NetworkCredential("sender#gmail.com", "Password");
smtp.EnableSsl = true;
smtp.Send(mail);
}

SMTP server not sending mail

I got Message that mail sent. But in Inbox there is no new email i have found that email in
server inetpub-> mailroot-> Queue
Please tell me the solution for this
Edited
public string btnSendmail()
{
// System.Web.Mail.SmtpMail.SmtpServer is obsolete in 2.0
// System.Net.Mail.SmtpClient is the alternate class for this in 2.0
SmtpClient smtpClient = new SmtpClient();
MailMessage message = new MailMessage();
try
{
MailAddress fromAddress = new MailAddress("myemail#itaxsmart.com","");
smtpClient.Host = "localhost";
smtpClient.Port = 25;
message.From = fromAddress;
message.To.Add("mailsendtol#itaxsmart.com");
message.Subject = "Feedback";
message.IsBodyHtml = false;
message.Body = "Hello World" ;
smtpClient.Send(message);
return "Email successfully sent.";
}
catch (Exception ex)
{ return "Send Email Failed." + ex.Message;
}
Is your SMTP started? If not, start it. If it is already started, try restarting it.
Also turn on logging and see if that helps.
The moment asp.net manages to sent the message to the smtp server, you will get a success message. This only means that the message has reached your smtp server.
asp.net cannot control what your smtp server does with it.
Try using a public smtp server like gmail, if your local smtp server is giving trouble.
Add This code to your web.config
<system.net>
<mailSettings>
<smtp>
<network host="relay-hosting.secureserver.net"/>
</smtp>
</mailSettings>
</system.net>
and Remove This
smtpClient.Host = "localhost";
smtpClient.Port = 25;
Thanks,
Subhankar

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