asp.net send mail in vb.net - asp.net

This is web config
<appSettings>
<add key="SmtpServer" value="gmail.com"/>
<add key="SmtpUtilisateur" value="superman#gmail.com"/>
<add key="SmtpPassword" value="12345678"/>
</appSettings>
This my vb method
Sub SendSimpleMail()
Dim Message As New Mail.MailMessage
Dim utilisateur As String
Dim pass As String
Dim server As String
utilisateur = ConfigurationSettings.AppSettings("StmpUtilisateur")
pass = ConfigurationSettings.AppSettings("SmtpPassword")
server = ConfigurationSettings.AppSettings("SmtpServer")
Message.From = "superman#gmail.com"
Message.To = "superman#gmail.com"
Message.Subject = "test"
Message.Body = "salut je voulais savoir comment tu allais"
Message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1")
Message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", utilisateur)
Message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtppassworld", pass)
SmtpMail.SmtpServer = server
Try
SmtpMail.Send(Message)
Catch ex As Exception
Label1.Text = ex.Message
End Try
End Sub
I get an error like the "transport fail in connection to server"
I don't know why this is not work well...
Thank's for helping me!
This in vb.net

First, it is recommended to use System.Net.Mail instead of SmtpMail, since the latter has been declared obsolete by Microsoft.
Second, the Gmail SMTP server requires a secure connection which can be set using SmtpClient.EnableSsl.
Your example could be changed to the following:
Sub SendSimpleMail()
Dim utilisateur As String = ConfigurationSettings.AppSettings("StmpUtilisateur")
Dim pass As String = ConfigurationSettings.AppSettings("SmtpPassword")
Dim server As String = ConfigurationSettings.AppSettings("SmtpServer")
Dim Message As New Mail.MailMessage()
Message.From = "superman#gmail.com"
Message.To = "superman#gmail.com"
Message.Subject = "test"
Message.Body = "salut je voulais savoir comment tu allais"
' You won't need the calls to Message.Fields.Add()
' Replace SmtpMail.SmtpServer = server with the following:
Dim client As New SmtpClient(server)
client.Port = 587
client.EnableSsl = true
client.Credentials = new System.Net.NetworkCredential(utilisateur,pass);
Try
client.Send(Message)
Catch ex As Exception
' ...
End Try
End Sub
If you replace the appsettings in the web.config with the following specific block, the SmtpClient will automatically configure itself accordingly:
<system.net>
<mailSettings>
<smtp from="superman#gmail.com">
<network host="smtp.gmail.com"
password="12345678"
userName="superman#gmail.com"
enableSsl="true"
port=587/>
</smtp>
</mailSettings>
</system.net>
This would reduce your method to:
Sub SendSimpleMail()
Dim Message As New Mail.MailMessage()
Message.To = "superman#gmail.com"
Message.Subject = "test"
Message.Body = "salut je voulais savoir comment tu allais"
Dim client As New SmtpClient()
Try
client.Send(Message)
Catch ex As Exception
' ...
End Try
End Sub

MailMessage msg = new MailMessage {From = new MailAddress(txtGAddress.Text, “Sender’s Name”)};
msg.To.Add(new MailAddress(txtTo.Text));
msg.Subject = txtSubject.Text;
msg.Body = txtMessage.Text;
msg.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient
{
Host = “smtp.gmail.com”,
Credentials = new NetworkCredential(txtGAddress.Text, txtGPassword.Text),
Port = 587,
EnableSsl = true
};
Label1.Visible = true;
try
{
smtp.Send(msg);
Label1.Text = “Email sent accessfully.”;
}
catch (Exception exeption)
{
Label1.Text = exeption.Message;
}

You will need to set the port number to be used when sending via gmail using the smtpserverport property
I think this is 587 for Google
Also I believe that gmail will require an SSL connection which you can set using the smtpusessl property

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

Operation has timed out error on ASP.NET

I'm getting an error while sending email through asp.net SMTP server. It says operation has timed out. How to overcome the exception?
try
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient();
mail.From = new MailAddress("mymailid#hotmail.com");
mail.To.Add("yourmailid#gmail.com");
mail.Subject = "Verify your account";
mail.Body = "Your OTP for your account verification is "+OTP.ToString()+". Enter your OTP in verification window.";
mail.IsBodyHtml = true;
SmtpServer.UseDefaultCredentials = false;
SmtpServer.Timeout = 20000;
SmtpServer.Send(mail);
errmsgShow.Text = "Mail sent";
}
catch (Exception e)
{
//string errMsg = "alert('OTP sending failed. Error: " +e.ToString()+ "')";
//ScriptManager.RegisterClientScriptBlock(Page, typeof(Page), "ClientScript", errMsg, true);
//Console.WriteLine(e.Message.ToString());
errmsgShow.Text = e.ToString();
}
I have also included below in the web.config
<system.net>
<mailSettings>
<smtp deliveryMethod="Network">
<network host="smtp.live.com" port="25" userName="mymailid#hotmail.com" password="password" enableSsl="true"/>
</smtp>
</mailSettings>
</system.net>
Try removing SmtpServer.Timeout = 20000;.
Update:
i see you have SmtpClient SmtpServer = new SmtpClient();.
SmtpServer is a property of SmtpMail SmtpMail.SmtpServer. Try changing the variable name, something like
SmtpClient mailClient = new SmtpClient();

error with sending mail vb.net

i'm having a problem with sending mail. my code is so easy as below.
when this code starts it gives the error:
Request for the permission of type 'System.Net.Mail.SmtpPermission,
System, Version=2.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089' failed.
when i searched for this error, they recommend changing web.config trust full setting or port from 587 to 25 and other stuff, but none work. what else could it be?
Sub MailGonder()
Dim SmtpServer As New SmtpClient()
Dim mail As New MailMessage()
SmtpServer.Host = "mail.excelinefendisi.com"
SmtpServer.Credentials = New Net.NetworkCredential("info#excelinefendisi.com", "mypassword")
SmtpServer.Port = 587
mail.From = New MailAddress("info#excelinefendisi.com")
mail.To.Add("volkan.yurtseven#hotmail.com")
mail.Subject = "Test Mail"
mail.Body = "This is for testing SMTP"
SmtpServer.EnableSsl = True
SmtpServer.Send(mail)
End Sub
Use this code, work perfect for me :
Dim iphost As IPHostEntry = Dns.GetHostByName(Dns.GetHostName())
Dim Emailmessage As New MailMessage()
Emailmessage.From = New MailAddress("from_Email#hotmail.com")
Emailmessage.To.Add("To_Email#hotmail.com")
Emailmessage.Subject = "tTest Mail"
Emailmessage.Body = ("This is for testing SMTP")
Dim smtp As New SmtpClient("smtp.live.com")
smtp.Port = 587
smtp.EnableSsl = True
smtp.Credentials = New System.Net.NetworkCredential("your_email#hotmail.com.com", "Password")
smtp.Send(Emailmessage)

Authenticated mail sending not working in .NET

I have a script sending mail from my .net application.
My hosting provider requires the emails to be authenticated if I don't want to cause delays in receiving them (currently delay is almost a day from sending).
I have build mail sending script with authentication but it doesn't work - it doesn't produce any error or exception but the emails are still not received instantly.
In the other hand similar script made in classic asp works and I receive mails instantly.
Am I missing something?
This is asp script (which works):
<%
Set objEmail = CreateObject("CDO.Message")
objEmail.From = "sender#mydomain.com"
objEmail.To = "recipient#gmail.com"
objEmail.Subject = "Test Mail"
objEmail.Textbody = "Test Mail"
objEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
objEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "mail.mydomain.com"
objEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
objEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = "1"
objEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusername") = "myusername"
objEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "mypassword"
objEmail.Configuration.Fields.Update
objEmail.Send
If Not err.number=0 Then
Response.write "ERROR: " & err.Description
err.Clear
end if
%>
This is .NEt (which doesn't work):
public static void SendEmail(string senderName, string senderEmail, string recipient, string comments, string subject, bool inTemplate)
{
MailAddress from = new MailAddress(senderEmail);
MailAddress to = new MailAddress(recipient);
MailMessage mail = new MailMessage(from, to);
mail.ReplyToList.Add(senderEmail);
mail.Subject = subject;
mail.IsBodyHtml = true;
mail.Body = comments;
Configuration configurationFile = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
MailSettingsSectionGroup mailSettings = configurationFile.GetSectionGroup("system.net/mailSettings") as MailSettingsSectionGroup;
NetworkCredential basicCredentials = new NetworkCredential(mailSettings.Smtp.Network.UserName, mailSettings.Smtp.Network.Password);
SmtpClient smtpClient = new SmtpClient();
smtpClient.Host = mailSettings.Smtp.Network.Host;
smtpClient.Port = mailSettings.Smtp.Network.Port;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = basicCredentials;
try
{
smtpClient.Send(mail);
}
catch (Exception ex)
{
throw ex;
}
}
These are my web.config settings:
<system.net>
<mailSettings>
<smtp>
<network host="mail.mydomain.com" userName="myusername" password="mypassword" port="25" />
</smtp>
</mailSettings>
</system.net>
The web.config settings are correct but even if I input server settings manually into the class - it doesn't work.
Thanks
Try this:
MailMessage mailMsg = new MailMessage();
mailMsg.To.Add("test#hotmail.com");
// From
MailAddress mailAddress = new MailAddress("you#hotmail.com");
mailMsg.From = mailAddress;
// Subject and Body
mailMsg.Subject = "subject";
mailMsg.Body = "body";
// Init SmtpClient and send on port 587 in my case. (Usual=port25)
SmtpClient smtpClient = new SmtpClient("mailserver", 587);
System.Net.NetworkCredential credentials =
new System.Net.NetworkCredential("username", "password");
smtpClient.Credentials = credentials;
smtpClient.Send(mailMsg);
It turned out that the problem was at the hosting provider side. Not sure what they did but it eventually started to work.

Unable to send in asp.net application

I want to send an e-mail, but it shows the following error:
try
{
string filename = Server.MapPath("~/App_Data/FeedBack.txt");
string mailbody = System.IO.File.ReadAllText(filename);
mailbody = mailbody.Replace("##Name##", txtName.Text);
mailbody = mailbody.Replace("##Email##",txtEmail.Text);
mailbody = mailbody.Replace("##contact##",txtContact.Text);
mailbody = mailbody.Replace("##Commnect##",txtSuggestion.Text);
MailMessage myMessage = new MailMessage();
myMessage.Subject = "Responce from website";
myMessage.Body = mailbody;
myMessage.From = new MailAddress("amitverma0511#gmail.com","Amit Kumar");
myMessage.To.Add(new MailAddress("amitverma1150#gmail.com", "Amit Verma"));
SmtpClient mysmptclient = new SmtpClient("localhost");
mysmptclient.Host = "smtp.gmail.com";
mysmptclient.Port = 587;
mysmptclient.Credentials = new System.Net.NetworkCredential("amitverma0511#gmail.com", "Myemailpassword");
mysmptclient.Send(myMessage);
formatTable.Visible = false;
lblMail.Text = "Your Feedback has been sent successfully";
lblMail.ForeColor = Color.Green;
}
catch(Exception expt)
{
lblMail.Text = "unable to sent the feedback .Check your smpt server"+expt.Message;
lblMail.ForeColor = Color.Red;
}
My web.config file looks like this:
<system.net>
<mailSettings>
<smtp from="amitverma0511#gmail.com">
<network host="smtp.gmail.com" port='587' password="myemailpass" userName="amitverma0511#gmail.com"/>
</smtp>
</mailSettings>
</system.net>
As far as I know, you are overwriting your web.config settings by using localhost (your IIS) as a SMTP Server.
If you have not configured your IIS to serve as a SMTP server this naturally will not work.
But, if you want to use localhost and not the google servers just use this 3 lines:
SmtpClient MySmtpClient = new SmtpClient();
MySmtpClient.UseDefaultCredentials = true;
MySmtpClient.Send(mailMessage);
You should remove the string localhost from SmtpClient mysmptclient = new SmtpClient("localhost"); and it should work, if all your other settings are correct.
Further information can be found here.

Resources