Activation email in vb.net identity - asp.net

I hope someone can shed some light for me, I have an application that users can register and have un-commented lines in the register.aspx.vb file to allow for email.
Protected Sub CreateUser_Click(sender As Object, e As EventArgs)
Dim userName As String = Email.Text
Dim manager = Context.GetOwinContext().GetUserManager(Of ApplicationUserManager)()
Dim signInManager = Context.GetOwinContext().Get(Of ApplicationSignInManager)()
Dim user = New ApplicationUser() With {.UserName = userName, .Email = userName}
Dim result = manager.Create(user, Password.Text)
If result.Succeeded Then
' For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
Dim code = manager.GenerateEmailConfirmationToken(user.Id)
Dim callbackUrl = IdentityHelper.GetUserConfirmationRedirectUrl(code, user.Id, Request)
manager.SendEmail(user.Id, "Confirm your account", "Please confirm your account by clicking here.")
signInManager.SignIn(user, isPersistent := False, rememberBrowser := False)
IdentityHelper.RedirectToReturnUrl(Request.QueryString("ReturnUrl"), Response)
Else
ErrorMessage.Text = result.Errors.FirstOrDefault()
End If
End Sub
The problem is though, that I need to add email settings similar to that at http://www.asp.net/identity/overview/features-api/account-confirmation-and-password-recovery-with-aspnet-identity#email but not sure how to call this, and does this need to go in the Identity.config under EmailService??? Do I need to add something to the web.config????

Add the details to your web.config:
<system.net>
<mailSettings>
<smtp from=“-your-sending-email-address-">
<network defaultCredentials="false" host=“-mail.example.com-" password=“—password-" userName=“—email—account-" />
</smtp>
</mailSettings>
</system.net>
More information:https://msdn.microsoft.com/en-us/library/w355a94k(v=vs.110).aspx

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

Email not working from Godaddy Server

First of all, I hope to be at the right place, I apologize in advance if this is not the case, please re-orient myself.
So here I have a worry, I have a website www.artipik.com with two forms, online quote and contact form.
My website is hosted by godaddy and servers were updated summers there for 15 days and my form are no longer work, which put me in a very problematic position. I'm a graphic designer not a coder, hence my difficulty changed the code.
I had the godaddy technical service and he gave it to me I think part of the solution. I found the place to change the code, but I can not seem to fit, I'm testing, I no further error messages but I do not receive any email I send.
My current ASP code is as follows:
<%
'-----version CDONTS-----
Set Mail = Server.CreateObject("CDONTS.NewMail")
Mail.BodyFormat = 1 '0:html/1:plain text
Mail.MailFormat = 1 '0:MIME/1:plain text
Mail.From = envoyeur
Mail.To = receveur
if copie<>vbnullstring then Mail.Bcc = copie
if sujet=vbnullstring then sujet="Formulaire de contact Artipik.com"
Mail.Subject = sujet
Mail.Body = message
Mail.Send
set Mail=Nothing
'response.cookies("email")=envoyeur
%>
and the new code that I have to adapt is the following (Using CDOSYS to Send Email from Your Windows Hosting Account):
// language -- C#
// import namespace
using System.Web.Mail;
private void SendEmail()
{
const string SERVER = "relay-hosting.secureserver.net";
MailMessage oMail = new System.Web.Mail.MailMessage();
oMail.From = "emailaddress#domainname";
oMail.To = "emailaddress#domainname";
oMail.Subject = "Test email subject";
oMail.BodyFormat = MailFormat.Html; // enumeration
oMail.Priority = MailPriority.High; // enumeration
oMail.Body = "Sent at: " + DateTime.Now;
SmtpMail.SmtpServer = SERVER;
SmtpMail.Send(oMail);
oMail = null; // free up resources
}
Thank you for your help.
Julian
System.Web.Mail.MailMessage is obsolete. You should use System.Net.Mail.MailMessage instead. It works almost exactly the same (warning! untested):
private void SendEmail()
{
using (var message = new MailMessage())
{
message.From = new MailAddress("emailaddress#domainname");
var toAddress = new MailAddress("emailaddress#domainname");
message.To.Add(toAddress);
message.Subject = "Test email subject";
message.Body = "Sent at: " + DateTime.Now;
message.Priority = MailPriority.High;
message.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Send(message);
}
}
Add this to your web.config:
<configuration>
<system.net>
<mailSettings>
<smtp from="emailaddress#domainname">
<network host="your-smtp-host-address" />
</smtp>
</mailSettings>
</system.net>
</configuration>
Recently I've had the same problem, could solve it throug the next way:
in web.config:
<system.net>
<mailSettings>
<smtp from="contacto#mydomain.com">
<network host="relay-hosting.secureserver.net" password="MyPass" port="25" enableSsl="false" defaultCredentials="false" userName="contacto#mydomain.com"/>
</smtp>
</mailSettings>
</system.net>
in codebehind:
MailMessage m = new MailMessage();
m.IsBodyHtml = true;
m.Body = "My Message";
m.To.Add("jhon.doe#yahoo.com");
m.Subject = "Go Daddy Emails Go Live!";
SmtpClient smtp = new SmtpClient();
smtp.Send(m);

asp.net send mail in vb.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

Email alert when page is open

Is there any way in asp.net that when my page is open on web then an email alert with username should be generate so that i have information that which one is accessing my page
I changed the code like bellow
Public Sub SendMail(ByVal id As String)
Dim message = New MailMessage()
message.IsBodyHtml = True
message.From = New MailAddress("adeel.aslam0#gmail.com")
message.[To].Add(New MailAddress("malik.adeel#shakarganj.com"))
message.Subject = "user access page"
message.Body = "Your Message"
' add id here
Dim client = New SmtpClient("smtp.gmail.com")
client.Send(message)
End Sub
and in web.config like this
<system.net>
<mailSettings>
<smtp from="adeel.aslam0#gmail.com">
<network host="smtp.gmail.com" defaultCredentials="false"
port="587" userName ="adeel.aslam0#gmail.com" password="pass" />
</smtp>
</mailSettings>
</system.net>
You might do something similar..
Modify your web.config file to send emails
e.g. This use gmail settings
<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>
And in your page_load
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
var user = HttpContext.Current.User;
if (user != null && user.Identity.IsAuthenticated)
{
var id = Membership.GetUser().ProviderUserKey;
SendMail(id.ToString());
}
}
}
public void SendMail(string id)
{
var message = new MailMessage();
message.IsBodyHtml = true;
message.From = new MailAddress("yourmail");
message.To.Add(new MailAddress("tomail"));
message.Subject= "user access page";
message.Body = "Your Message";// add id here
var client = new SmtpClient();
client.Send(message);
}
if you using vb try something like this.
This way, you will not need to change your web.config
Dim mailobject As New System.Net.Mail.MailMessage()
Dim myCred As New System.Net.NetworkCredential("yourmail#gmail.com", "password")
mailobject.To.Add("tomail")
mailobject.Subject = "User Access The Page"
mailobject.From = New System.Net.Mail.MailAddress("frommail")
mailobject.IsBodyHtml = True
mailobject.Body = "Your Message"
Dim SmtpMail As New System.Net.Mail.SmtpClient("smtp.gmail.com")
SmtpMail.UseDefaultCredentials = False
SmtpMail.EnableSsl = True
SmtpMail.Credentials = myCred
SmtpMail.Port = 587
SmtpMail.Send(mailobject)
Fair question. But you really do not want to do this unless you have a very limited amount of visitors. See the answer above on how to do it.
Better write everything into a table and send yourself a digest at certain interval per hour/day. This way you can also do some reporting afterwards using that table.

How to use gmail SMTP in ASP.NET form

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.

Resources