The server response was: 5.7.0 Must issue a STARTTLS command first. i16sm1806350pag.18 - gsmtp
Asked Answered
R

17

68

I am trying to send mail using gmail, and I am getting an exception that is The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.0 Must issue a STARTTLS command first. i16sm1806350pag.18 - gsmtp

code I have written for sending mail is:

MailMessage mail = new MailMessage(); 
mail.To.Add(txtEmail.Text.Trim()); 
mail.To.Add("[email protected]");
mail.From = new MailAddress("[email protected]");
mail.Subject = "Confirmation of Registration on Job Junction.";
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.gmail.com", 587);
// smtp.Host = "smtp.gmail.com"; //Or Your SMTP Server Address
smtp.Credentials = new System.Net.NetworkCredential("[email protected]", "password");
// smtp.Port = 587;
//Or your Smtp Email ID and Password
smtp.UseDefaultCredentials = false;
// smtp.EnableSsl = true;
smtp.Send(mail);

Please tell me solutions, I am not getting any solutions for this exception.

Rebarbative answered 4/7, 2013 at 5:41 Comment(3)
Hello @Ankur, If you get the solution of your problem then please help me, because I am getting the same error.Trinatte
@Trinatte there was SmtpClient Issue i have added smtp into web.confg and its resolved like in answers.Rebarbative
@AnkurGupta - Please explain me exactly how to do it. Thanks!Writeoff
S
68

Step (1): smtp.EnableSsl = true;

if not enough:

Step (2): "Access for less secure apps" must be enabled for the Gmail account used by the NetworkCredential using google's settings page:

Support answered 26/5, 2016 at 9:18 Comment(0)
H
45

Gmail requires you to use a secure connection. This can be set in your web.config like this:

<network host="smtp.gmail.com" enableSsl="true" ... />

OR

The SSL should be enable on the webserver as well. Refer following link

Enabling SSL on IIS 7.0

Hally answered 4/7, 2013 at 7:2 Comment(0)
S
12

This issue haunted me overnight as well. Here's how to fix it:

  • Set host to: smtp.gmail.com
  • Set port to: 587

This is the TLS Port. I had been using all of the other SMTP ports with no success. If you set enableSsl = true like this:

Dim SMTP As New SmtpClient(HOST)
SMTP.EnableSsl = True

Trim the username and password fields (good way to prevent errors if user inputs the email and password upon registering like mine does) like this:

SMTP.Credentials = New System.Net.NetworkCredential(EmailFrom.Trim(), EmailFromPassword.Trim())

Using the TLS Port will treat your SMTP as SMTPS allowing you to authenticate. I immediately got a warning from Google saying that my email was blocking an app that has security risks or is outdated. I proceeded to "Turn on less secure apps". Then I updated the information about my phone number and google sent me a verification code via text. I entered it and voila!

I ran the application again and it was successful. I know this thread is old, but I scoured the net reading all the exceptions it was throwing and adding MsgBoxes after every line to see what went wrong. Here's my working code modified for readability as all of my variables are coming from MySQL Database:

Try
    Dim MySubject As String = "Email Subject Line"
    Dim MyMessageBody As String = "This is the email body."
    Dim RecipientEmail As String = "[email protected]"
    Dim SenderEmail As String = "[email protected]"
    Dim SenderDisplayName As String = "FirstName LastName"
    Dim SenderEmailPassword As String = "SenderPassword4Gmail"

    Dim HOST = "smtp.gmail.com"
    Dim PORT = "587" 'TLS Port
    
    Dim mail As New MailMessage
    mail.Subject = MySubject
    mail.Body = MyMessageBody
    mail.To.Add(RecipientEmail) 
    mail.From = New MailAddress(SenderEmail, SenderDisplayName)

    Dim SMTP As New SmtpClient(HOST)
    SMTP.EnableSsl = True
    SMTP.Credentials = New System.Net.NetworkCredential(SenderEmail.Trim(), SenderEmailPassword.Trim())
    SMTP.DeliveryMethod = SmtpDeliveryMethod.Network 
    SMTP.Port = PORT
    SMTP.Send(mail)
    MsgBox("Sent Message To : " & RecipientEmail, MsgBoxStyle.Information, "Sent!")
Catch ex As Exception
    MsgBox(ex.ToString)
End Try

I hope this code helps the OP, but also anyone like me arriving to the party late. Enjoy.

Saunders answered 4/9, 2016 at 17:10 Comment(0)
S
9

"https://www.google.com/settings/security/lesssecureapps" use this link after log in your gmail account and click turn on.Then run your application,it will work surely.

Soho answered 22/7, 2016 at 7:40 Comment(2)
This answer pointed me in the right direction. Because I have 2fa activated for google mail I had to create a separate app password. Makes sense regarding security.Celesta
Thank you for the link! The setting is buried in a ton of extra bs.Volteface
C
5

SEND Button logic:

string fromaddr = "[email protected]";
string toaddr = TextBox1.Text;//TO ADDRESS HERE
string password = "YOUR PASSWROD";

MailMessage msg = new MailMessage();
msg.Subject = "Username &password";
msg.From = new MailAddress(fromaddr);
msg.Body = "Message BODY";
msg.To.Add(new MailAddress(TextBox1.Text));
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.UseDefaultCredentials = false;
smtp.EnableSsl = true;
NetworkCredential nc = new NetworkCredential(fromaddr,password);
smtp.Credentials = nc;
smtp.Send(msg);

This code work 100%. If you have antivirus in your system or firewall that restrict sending mails from your system so disable your antivirus and firewall. After this run this code... In this above code TextBox1.Text control is used for TOaddress.

Comprehend answered 12/3, 2015 at 14:8 Comment(1)
Sorry to be naieve but how does turning off firewall do anything? Surely when it goes on the hosting the developers firewall wont make a difference? Then it would be up to each user to have no firewall?Teodora
G
4

For very basic users like me the email from (FromEmailAddress) is actual email address created on Gmail and you also need to set Less secure app access in order for it to work. https://myaccount.google.com/lesssecureapps

Then the order of statements should also be correct.

    public static bool SendEmail(string body, string subject, string toEmail)
            {
                MailAddress fromAddress = new MailAddress("[email protected]", "Mail Support");
                MailAddress toAddress = new MailAddress(toEmail, "Dear Customer");
                const string fromPassword = "mymail_login_password.";
                SmtpClient smtpClient = new SmtpClient();
                smtpClient.UseDefaultCredentials = false;
                smtpClient.Credentials = new NetworkCredential(fromAddress.Address, fromPassword);
                smtpClient.Host = "smtp.gmail.com";
                smtpClient.Port = 587;
                smtpClient.EnableSsl = true;
                smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
                MailMessage mailMessage = new 
MailMessage(fromAddress.Address,toAddress.Address,subject, body);
                try
                {
                    smtpClient.Send(mailMessage);
                    return true;
                }
                catch (SmtpException ex)
                {
                      return false;
                }
            }
Gutierrez answered 6/1, 2022 at 7:55 Comment(0)
C
3

If you are passing (like me) all the parameters like port, username, password through a system and you are not allow to modify the code, then you can do that easy change on the web.config:

<system.net>
  <mailSettings>
    <smtp>
      <network enableSsl="true"/>
    </smtp>
  </mailSettings>
</system.net>
Caro answered 3/11, 2017 at 21:2 Comment(1)
Thanks for this, just wanted to add if anyone else runs into this when it comes to taking legacy code that doesn't support TLS 1.2 and using Microsoft 365 for email. Microsoft has a legacy endpoint for SMTP that needs to be turned on. learn.microsoft.com/en-us/exchange/…Dorpat
L
3

If you get the error "Unrecognized attribute 'enableSsl'" when following the advice to add that parameter to your web.config. I found that I was able to workaround the error by adding it to my code file instead in this format:

SmtpClient smtp = new SmtpClient();
smtp.EnableSsl = true;

try
{
    smtp.Send(mm);
}
catch (Exception ex)
{
    MsgBox("Message not emailed: " + ex.ToString());
}

This is the system.net section of my web.config:

<system.net>
  <mailSettings>
    <smtp from="<from_email>">
      <network host="smtp.gmail.com"
       port="587"
       userName="<your_email>"
       password="<your_app_password>" />
    </smtp>
  </mailSettings>
</system.net>
Limbic answered 30/3, 2018 at 21:45 Comment(0)
C
3

I also got the same error using the code:

MailMessage mail = new MailMessage(); 
mail.To.Add(txtEmail.Text.Trim()); 
mail.To.Add("[email protected]");
mail.From = new MailAddress("[email protected]");
mail.Subject = "Confirmation of Registration on Job Junction.";
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.gmail.com", 587);
// smtp.Host = "smtp.gmail.com"; //Or Your SMTP Server Address
smtp.Credentials = new System.Net.NetworkCredential("[email protected]", "password");
// smtp.Port = 587;
//Or your Smtp Email ID and Password
smtp.UseDefaultCredentials = false;
// smtp.EnableSsl = true;
smtp.Send(mail);

But moving 2 lines upward fixed the problem:

MailMessage mail = new MailMessage(); 
mail.To.Add(txtEmail.Text.Trim()); 
mail.To.Add("[email protected]");
mail.From = new MailAddress("[email protected]");
mail.Subject = "Confirmation of Registration on Job Junction.";
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.gmail.com", 587);
// smtp.Host = "smtp.gmail.com"; //Or Your SMTP Server Address
smtp.UseDefaultCredentials = false;
smtp.EnableSsl = true;
smtp.Credentials = new System.Net.NetworkCredential("[email protected]", "password");
// smtp.Port = 587;
//Or your Smtp Email ID and Password
smtp.Send(mail);
Crossroads answered 8/8, 2018 at 14:56 Comment(1)
I don't know how it worked for you. I am still getting exact same issue.Swine
T
2

Loginto your gmail account https://myaccount.google.com/u/4/security-checkup/4

enter image description here

(See photo) review all locations Google may have blocked for "unknown" or suspicious activity.

Trophic answered 9/12, 2019 at 15:14 Comment(1)
Also turn "less secure app access" on. then use SSL.Cabochon
A
1

If you don't have 2 factor

Enable "Less Secure Apps"

https://www.google.com/settings/security/lesssecureapps

If you have 2 factor authentication

You can make an "App Password". Go to the ling below and add a custom app (just write any name you want, name not important just used for your own "bookkeeping") then use that password as the password.

client.Credentials = new NetworkCredential("[email protected]", "Generated Password");

https://security.google.com/settings/u/1/security/apppasswords

NOTE: If you get "The setting you are looking for is not available for your account" then use "less secure app"

Abloom answered 24/12, 2022 at 15:46 Comment(0)
A
0
**this is first  part of program**
<head runat="server">
    <title></title>
    <style>
        .style4
        {
            margin-left:90px;
        }
        .style3{
            margin-left:130px;
        }
        .style2{
            color:white;
            margin-left:100px;
            height:400px;
            width:450px;
            text-align:left;
                }
        .style1{
            height:450px;
            width:550px;
            margin-left:450px;
            margin-top:100px;
            margin-right:500px;
            background-color:rgba(0,0,0,0.9);
        }
        body{
            margin:0;
            padding:0;
        }
        body{
            background-image:url("/stock/50.jpg");
            background-size:cover;
            background-repeat:no-repeat;
            }   
       </style>
</head>
<body>
    <form id="form1" runat="server">
        <div>

            <div class="style1">
                <table class="style2">
                   <tr>
                       <td colspan="2"><h1 class="style4">Sending Email</h1></td>
                   </tr>
                   <tr>
                       <td>To</td>
                       <td><asp:TextBox ID="txtto" runat="server" Height="20px" Width="250px" placeholder="[email protected]"></asp:TextBox><asp:RequiredFieldValidator ForeColor="Red" runat="server" ErrorMessage="Required" ControlToValidate="txtto" Display="Dynamic"></asp:RequiredFieldValidator><asp:RegularExpressionValidator runat="server" ForeColor="Red" ControlToValidate="txtto" Display="Dynamic" ErrorMessage="Invalid Email_ID" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator> </td>
                   </tr>
                     <tr>
                       <td>From</td>
                       <td><asp:TextBox ID="txtfrom" runat="server" Height="20px" Width="250px" placeholder="[email protected]"></asp:TextBox> <asp:RequiredFieldValidator ForeColor="Red" Display="Dynamic" runat="server" ErrorMessage="Required" ControlToValidate="txtfrom"></asp:RequiredFieldValidator>
                           <asp:RegularExpressionValidator Display="Dynamic" runat="server" ErrorMessage="Invalid Email-ID" ControlToValidate="txtfrom" ForeColor="Red" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>
                         </td>
                   </tr>
                     <tr>
                       <td>Subject</td>
                       <td><asp:TextBox ID="txtsubject" runat="server" Height="20px" Width="250px" placeholder="Demonstration on Youtube"></asp:TextBox><asp:RequiredFieldValidator ForeColor="Red" runat="server" ErrorMessage="Required" ControlToValidate="txtsubject"></asp:RequiredFieldValidator> </td>
                   </tr>
                     <tr>
                       <td>Body</td>
                       <td><asp:TextBox ID="txtbody" runat="server" Width="250px" TextMode="MultiLine" Rows="5" placeholder="This is the body text"></asp:TextBox><asp:RequiredFieldValidator ForeColor="Red" runat="server" ErrorMessage="Required" ControlToValidate="txtbody"></asp:RequiredFieldValidator> </td>
                   </tr>
                     <tr>
                       <td colspan="2"><asp:Button CssClass="style3" BackColor="Green" BorderColor="green" ID="send" Text="Send" runat="server" Height="30px"  Width="100px" OnClick="send_Click"/></td>
                     </tr>
                    <tr>
                        <td colspan="2"><asp:Label ID="lblmessage" runat="server"></asp:Label> </td>
                    </tr>
               </table>
            </div>

        </div>
    </form>
</body>
</html>


**this is second part of program**

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;

namespace WebApplication6
{
    public partial class sendingemail1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void send_Click(object sender, EventArgs e)
        {
            try
            {
                MailMessage message = new MailMessage();
                message.To.Add(txtto.Text);
                message.Subject = txtsubject.Text;
                message.Body = txtbody.Text;
                message.From = new MailAddress(txtfrom.Text);
                SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
                client.EnableSsl = true;
                client.Credentials = new System.Net.NetworkCredential(txtfrom.Text, "Sunil@123");
                for(int i=1;i<=100;i++)
                { 
                client.Send(message);
                lblmessage.Text = "Mail Successfully send";
                }
            }
            catch (Exception ex)
            {
                lblmessage.Text = ex.Message;
            }
        }
    }
}
Aura answered 22/5, 2019 at 10:24 Comment(1)
Welcome to Stack Overflow! Generally, answers are much more helpful if they include an explanation of what the code is intended to do, and why that solves the problem without introducing others.Joubert
J
0

i Create new E-mail without any phone number or related E-mail then Turn ON less secure app access that done with me

Jimjams answered 8/5, 2020 at 13:51 Comment(0)
O
0

Note to self: "Remove UseDefaultCredentials = false".

Ontiveros answered 7/7, 2020 at 7:13 Comment(0)
A
0

If you are using database mail . In manage database mail account select requires secure connection checkbox.

Amygdaloid answered 25/4, 2022 at 8:55 Comment(0)
S
0

Enable TLS v 1.1 and 1.2 in your code

https://iq.direct/blog/316-how-to-enable-tls-v1-2-in-net-framework-4-0.html

Skippy answered 6/9, 2022 at 20:11 Comment(0)
B
0

The solution of raminjacobson is brilliant

in c#

System.Net.ServicePointManager.SecurityProtocol = (System.Net.SecurityProtocolType)(768 | 3072);

in vb.net

System.Net.ServicePointManager.SecurityProtocol = CType((768 Or 3072), System.Net.SecurityProtocolType)

Budweis answered 29/11, 2022 at 10:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.