Can someone help me pls. I am ready to deploy my web application. I have a contact form that i want users to send me a message. Ive created the smtp when i click on submit, i get the error message cannot be sent.
The application is still on my local machine maybe thats why. But i just want to know if this code is good for my form:
Imports System.Net.Mail
Partial Class contact
Inherits System.Web.UI.Page
Protected Sub CustomValidator1_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles CustomValidator1.ServerValidate
If txtComments.Text.Length > 300 Then
args.IsValid = False
Else
args.IsValid = True
End If
End Sub
Protected Sub Wizard1_FinishButtonClick(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.WizardNavigationEventArgs) Handles Wizard1.FinishButtonClick
SendMail(txtEmail.Text, txtComments.Text)
End Sub
Private Sub SendMail(ByVal from As String, ByVal body As String)
Dim mailServerName As String = "SMTP.relay-hosting.secureserver.net"
Dim message As MailMessage = New MailMessage(from, "collins#collinsegbe.com", "feedback", body)
Dim mailClient As SmtpClient = New SmtpClient
mailClient.Host = mailServerName
mailClient.Send(message)
message.Dispose()
End Sub
End Class
The error is indicated on this line of code: mailClient.Send(message)
I will appreciate help from anyone
protected void Button9_Click(object sender, EventArgs e)
{
{
var fromAddress = new MailAddress("rusty109.stud#gmail.com");
var toAddress = new MailAddress(TextBox13.Text);
const string fromPassword = "commando1";
string subject = TextBox14.Text;
string body = TextBox12.Text;
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(fromAddress.Address, fromPassword),
Timeout = 20000
};
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body
})
{
smtp.Send(message);
}
}
}
my old code when i wanted to email, you can use the gmail account if you wish, nothing in it... was set up to use this code :)
using System.Net.Mail;
using System.Net;
You need to add the username and password for the SMTP server by setting the SmtpClient's Credential property to an instance of the NetworkCredential class.
Related
I want to invoke method (to sending a mail) in session_start.
This is my task function:
Public Shared Async Function SendEmailMessage(ByVal MailFrom As String, ByVal MailTo As String, ByVal Subject As String, ByVal HtmlMessage As String) As Task
Dim mail As MailMessage = New MailMessage
mail.From = New MailAddress(MailFrom)
mail.To.Add(MailTo)
mail.Subject = Subject
mail.Body = HtmlMessage
Dim smtp As SmtpClient = New SmtpClient("smtpclient")
smtp.Port = 587
smtp.DeliveryMethod = SmtpDeliveryMethod.Network
smtp.UseDefaultCredentials = True
Await Task.Run(Function() smtp.SendMailAsync(mail))
'Await result
End Function
In global.asax i have this code:
Public Overrides Sub Init()
MyBase.Init()
Dim wrapper = New EventHandlerTaskAsyncHelper(AsyncSessionStart)
Me.AddOnAcquireRequestStateAsync(wrapper.BeginEventHandler, wrapper.EndEventHandler)
End Sub
Private Async Function AsyncSessionStart() As Task
If Not Session.IsNewSession Then Return
Await funzioni.SendEmailMessage("***#***.**", "*****#***", "Object text",
String.Format("E' stato effettuato un tentativo di accesso da {0} del {1} alla WebApp.",
Session("name"), Session("office")))
End Function
this is the reference text that I have read and followed asp-net-async-global-asax
visual studio, however, gives me the following error in this part of the code:
Dim wrapper = New EventHandlerTaskAsyncHelper(AsyncSessionStart)
Value of type Task cannot be converted to TaskEventHandler.
where am i wrong?
Without having tested, I believe that this:
Private Async Function AsyncSessionStart() As Task
should be this:
Private Async Sub AsyncSessionStart(sender As Object, e As EventArgs)
The method you specify to the EventHandlerTaskAsyncHelper constructor should be an asynchronous event handler, which means using the standard event handler parameters (which the link you posted does but you ignored) and declaring it an Async Sub.
You also have to use the AddressOf operator to create a delegate in VB. You may also have to specify the delegate type explicitly:
Dim wrapper = New EventHandlerTaskAsyncHelper(AddressOf AsyncSessionStart)
or:
Dim wrapper = New EventHandlerTaskAsyncHelper(New TaskEventHandler(AddressOf AsyncSessionStart))
I am trying to authenticate my application with Identity Server Version 3. But, when I do, I get an error. Here is my code:
Startup.Auth.vb:
Partial Public Class Startup
Public Sub ConfigureAuth(app As IAppBuilder)
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType)
app.UseCookieAuthentication(New CookieAuthenticationOptions())
app.UseOpenIdConnectAuthentication(New OpenIdConnectAuthenticationOptions() With {
.ClientId = clientId,
.Authority = authority,
.RedirectUri = "https://localhost:44321/",
.Scope = OpenIdConnectScope.OpenIdProfile,
.ResponseType = OpenIdConnectResponseType.IdToken,
.TokenValidationParameters = New TokenValidationParameters() With {
.ValidateIssuer = False
},
.Notifications = New OpenIdConnectAuthenticationNotifications() With {
.AuthenticationFailed = AddressOf OnAuthenticationFailed
}
})
End Sub
Private Function OnAuthenticationFailed(ByVal context As AuthenticationFailedNotification(Of OpenIdConnectMessage, OpenIdConnectAuthenticationOptions)) As Task
context.HandleResponse()
context.Response.Redirect("/?errormessage=" & context.Exception.Message)
Return Task.FromResult(0)
End Function
end class
Login Page:
Protected Sub manuanSignIn(ByVal sender As Object, ByVal e As EventArgs) Handles manualLogin.Click
If (Not Request.IsAuthenticated) Then
Dim newAuth As AuthenticationProperties = New AuthenticationProperties()
newAuth.RedirectUri = "/"
HttpContext.Current.GetOwinContext().Authentication.Challenge(newAuth, OpenIdConnectAuthenticationDefaults.AuthenticationType)
End If
End Sub
The Error I get, when I attempt to login, is:
An existing connection was forcibly closed by the remote host
Anyone have ideas on what is causing this and how to fix it?
Adding this fixed the issue:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12
We are working adding real time push notification to Asp.net web application.
I'm able to broadcast one message to all the users who is logged in to website.
but I'm not able to send notification to only one particular user based on the value inserted in the database table.
when i try to do this it's updating all the clients whoever is logged currently.
My code sample below:
SqlDependency Component:
Public Sub RegisterNotification(ByVal currentTime As DateTime)
Try
Dim conStr = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Dim sqlCommand = "SELECT [seq_id],[user_id],[create_timestamp],[alert_read] FROM [dbo].[tblAlerts] WHERE [alert_read]=0 AND [create_timestamp] > #AddedOn"
Using con As New SqlConnection(conStr)
Dim cmd As New SqlCommand(sqlCommand, con)
cmd.Parameters.AddWithValue("#AddedOn", currentTime)
If con.State <> Data.ConnectionState.Open Then
con.Open()
End If
cmd.Notification = Nothing
Dim dependency As New SqlDependency(cmd)
AddHandler dependency.OnChange, AddressOf sqlDep_OnChange
Using reader As SqlDataReader = cmd.ExecuteReader()
Do nothing here
End Using
End Using
Catch ex As Exception
Throw ex
End Try
End Sub
Sub sqlDep_OnChange(ByVal sender As Object, ByVal e As SqlNotificationEventArgs)
Try
If e.Info = SqlNotificationInfo.Insert Then
Dim notificationHub = GlobalHost.ConnectionManager.GetHubContext(Of NotificationHub)
Dim userid = Membership.GetUser.ProviderUserKey
notificationHub.Clients.All.notify(userid)
End If
Dim depend = DirectCast(sender, SqlDependency)
RemoveHandler depend.OnChange, AddressOf sqlDep_OnChange
RegisterNotification(DateTime.UtcNow)
Catch ex As Exception
End Try
End Sub
Notification Hub Code
Public Class NotificationHub
Inherits Hub
Public Sub showdata(ByVal obj As Object)
Try
Dim userobj = obj
Dim notificationHub = GlobalHost.ConnectionManager.GetHubContext(Of NotificationHub)
Dim count = 0
take count from database for userid in the object
notificationHub.Clients.All.setcount(count)
Catch ex As Exception
End Try
End Sub
End Class
SignalR Js code
$(function () {
// signalr js code for start hub and send receive notification
var notificationHub = $.connection.notificationHub;
notificationHub.client.setCount = function (data) {
$('span.count').html(data);
}
$.connection.hub.start().done(function () {
console.log('Notification hub started');
});
//signalr method for push server message to client
notificationHub.client.notify = function (message) {
if (message) {
notificationHub.server.showdata(message);
}
}
})
I have also noticed one more thing here is , sqlDep_OnChange event is called more than once if i have opened applicaiton in more than one browser.
I have managed to do the same with following link:
https://learn.microsoft.com/en-us/aspnet/signalr/overview/guide-to-the-api/mapping-users-to-connections
Using SignalR v2 you can use the connectionID to find the corresponding user.
Have created a simple contact form for use on client's website and can get the email (i'm using my gmail account temporarily) but when it is sent it shows it is from me no matter what I put in the email field. Please help! Probably something completely ignorant but please help! I want the email to be derived from the txtEmail.text field. Is there something I need to add to my web.config or on GoDaddy side of things? Thanks. Below is my code. I am aware I need to include try catch and clear the fields, but that will come after I get this to work!! And yes I did include my real credentials.
Imports System.Net.Mail.MailAddress
Imports System.Net.Mail.MailMessage
Imports System.Net.NetworkCredential
Imports System.Net.Mail
Partial Class Default2
Inherits System.Web.UI.Page
Protected Sub btnSubmit_Click1(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click
Dim Msg As New MailMessage()
' Sender e-mail address.
Msg.From = New MailAddress(txtEmail.Text)
' Recipient e-mail address.
Msg.To.Add("lchevy5#gmail.com")
Msg.Subject = txtSubject.Text
Msg.Body = "Sent From:" & txtName.Text + Environment.NewLine + "Email:" & txtEmail.Text + Environment.NewLine + txtMessage.Text
' your remote SMTP server IP.
Dim smtp As New SmtpClient()
smtp.Host = "smtp.gmail.com"
smtp.Port = 25
smtp.Credentials = New System.Net.NetworkCredential("user", "pass")
smtp.EnableSsl = True
smtp.Send(Msg)
'Msg = null;
lbltexts.Visible = True
End Sub
End Class
Your code looks correct, but you're sending it through Gmail. Their SMTP server is likely rewriting the FROM field so that it matches the email address you're using for authentication.
You might want to see this question.
Alternatively, you can send your mail through an SMTP server that doesn't do this.
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles
Button2.Click
Dim MyMessage As New MailMessage
Try
MyMessage.From = New MailAddress(TextBox2.Text)
MyMessage.To.Add("Example#gmail.com")
MyMessage.Subject = TextBox3.Text + body
MyMessage.Body = TextBox4.Text
Dim SMTP As New SmtpClient("smtp.gmail.com")
SMTP.Port = 587
SMTP.EnableSsl = True
SMTP.Credentials = New System.Net.NetworkCredential("Example#gmail.com", "Password")
SMTP.Send(MyMessage)
MessageBox.Show("Success")
Catch ex As Exception
MessageBox.Show("failed To Send")
End Try
End Sub
Try this Code for Send Email For Your Specified Mail Id
I am using VS2012 with ASP.NET 4.5 and MySQL as my database provider.
I am getting a specified cast error now on code that was working fine at one point.
It is from my Register.aspx page for registration verification and the code is adapted from an asp.net website tutorial.
Here is the code, the error is on the Dim newUser as Guid line
Protected Sub RegisterUser_CreatedUser(ByVal sender As Object, ByVal e As EventArgs) Handles RegisterUser.CreatedUser
FormsAuthentication.SetAuthCookie(RegisterUser.UserName, False)
Dim newUser As MembershipUser = Membership.GetUser(RegisterUser.UserName)
Dim newUserID As Guid = DirectCast(newUser.ProviderUserKey, Guid)
Dim urlBase As String = Request.Url.GetLeftPart(UriPartial.Authority) & Request.ApplicationPath
Dim verifyUrl As String = "VerifyNewUser.aspx?ID=" & newUserID.ToString()
Dim fullPath As String = urlBase & verifyUrl
Dim appPath As String = Request.PhysicalApplicationPath
Dim sr As New StreamReader(appPath & "EmailTemplates/VerifyUserAccount.txt")
Dim mailMessage As New MailMessage()
mailMessage.IsBodyHtml = True
mailMessage.From = New MailAddress("myacct#gmail.com")
mailMessage.To.Add(New MailAddress(RegisterUser.Email))
mailMessage.CC.Add(New MailAddress("myacct#gmail.com"))
mailMessage.Subject = "New User Registration"
mailMessage.Body = sr.ReadToEnd
sr.Close()
mailMessage.Body = mailMessage.Body.Replace("<%UserName%>", RegisterUser.UserName)
mailMessage.Body = mailMessage.Body.Replace("<%VerificationUrl%>", fullPath)
//Set up the smtp for gmail to send the email
Dim mailClient As New SmtpClient()
With mailClient
.Port = 587 'try 465 if this doesn't work
.EnableSsl = True
.DeliveryMethod = SmtpDeliveryMethod.Network
.UseDefaultCredentials = False
.Credentials = New NetworkCredential(mailMessage.From.ToString(), "password")
.Host = "smtp.gmail.com"
End With
mailClient.Send(mailMessage)
Dim continueUrl As String = RegisterUser.ContinueDestinationPageUrl
If String.IsNullOrEmpty(continueUrl) Then
continueUrl = "~/"
End If
Response.Redirect(continueUrl)
End Sub
When you, or anyone, creates a MembershipProvider you need to specify whether the ProviderUserKey is going to be an integer or a Guid. The default SqlMembershipProvider implements it a a Guid while the default MySqlMembershipProvider implements it as an int.
You could always implement your own provider by inheriting from one of the defaults and implementing your own version of the ProviderUserKey