Contact Form password security - asp.net

I created a contact form and have a security question for this form.
I did some research for my question already, but I want to double-check before I make any mistakes...
Basically, I created my contact form in my code behind as follows.
In there, I would have to include my Email address and my password to get connected to the smtp server.
I am afraid it's easy to find out my credentials.
Does anybody have a recommendation for how to secure this code? (Or am I dead wrong with this solution anyways?)
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
End Sub
Protected Sub Button_Click(ByVal sender As Object, ByVal e As EventArgs)
Try
If Page.IsValid Then
Dim mailMessage As New MailMessage()
mailMessage.From = New MailAddress("MYEMAILADRESS")
mailMessage.To.Add("MYEMAILADRESS")
mailMessage.Subject = txtSubject.Text
mailMessage.Body = "<b>Sender Name : </b>" & txtName.Text & "<br/>" & "<b>Sender Email : </b>" & txtEmail.Text & "<br/>" & "<b>Phone </b>" & txtPhone.Text & "<br/>" & "<b>Comments : </b>" & txtComments.Text
mailMessage.IsBodyHtml = True
Dim smtpClient As New SmtpClient("smtp.gmail.com", 587)
smtpClient.EnableSsl = True
smtpClient.Credentials = New System.Net.NetworkCredential("MYEMAILADRESS", "PASSWORD")
smtpClient.Send(mailMessage)
Label.Text = "Thank you for contacting us"
txtName.Enabled = False
txtEmail.Enabled = False
txtComments.Enabled = False
txtSubject.Enabled = False
txtPhone.Enabled = False
Button.Enabled = False
End If
Catch ex As Exception
'Log - Event Viewer or table
Label.Text = "There is an unknown problem, please try later"
End Try
End Sub

As was alluded to in the comments, you'll want to move a lot of these values to a config file, including your password. Ideally, you will store the credentials in an encrypted format so that if someone steals your config file, they can't access your email.
See this answer for directions on how to encrypt it: Encrypting Web.Config
Detailing how to encrypt/decrypt the file is a bit out of scope for this question, but I think it is the right path for you to go down.

Related

Streaming PDF works on Localhost but not on published Website

I'm currently trying to open a PDF file on my website that is located on my company's network. I had this working previously, but now for some reason it isn't working. Here is what I have:
I am using impersonation to access the file. It has domain admin privileges. This is from my web.config file (username/password are altered):
<identity impersonate="true" password="pass" userName="domain\user" />
I use this code to open the PDF in a window:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Try
Dim strPath As String = CStr(Session("DWGPath"))
strPath = "file://san01/prodeng/" + Mid(strPath, 4)
strPath = Replace(strPath, "\", "/")
Dim pdfPath As String = strPath
Dim client As WebClient = New WebClient()
Dim buffer As Byte() = client.DownloadData(pdfPath)
Response.ContentType = "application/pdf"
Response.AddHeader("content-length", buffer.Length.ToString())
Response.BinaryWrite(buffer)
Response.End()
Catch exa As WebException
Response.Redirect("DrawingError.aspx")
Catch ex As Exception
Throw ex
End Try
End Sub
This doesn't work. It redirects me to the "DrawingError.aspx" page. This link dispalys the "Session("DWGPath")" variable. I can take this variable and paste it in to my browser and the PDF opens without problem.
However, if I alter my code to this:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Try
Dim strPath As String = CStr(Session("DWGPath"))
Dim pdfPath As String = strPath
Dim client As WebClient = New WebClient()
Dim buffer As Byte() = client.DownloadData(pdfPath)
Response.ContentType = "application/pdf"
Response.AddHeader("content-length", buffer.Length.ToString())
Response.BinaryWrite(buffer)
Response.End()
Catch exa As WebException
Response.Redirect("DrawingError.aspx")
Catch ex As Exception
Throw ex
End Try
End Sub
It still doesn't work.
The account also has full control privileges to the folder that contains the PDFs.
Any help or insight would be appreciated. Thank you!
EDIT: IF I throw exa then I get this:
The account used is a computer account. Use your global user account or local user account to access this server.
I assume you're running IIS. Go to the application pool for this app and change the identity that it's running under to be the domain\user account. See if that fixes your problem.
You want to make sure that the password on this account doesn't change or else it will fail when the password expires.

Variable 'std' is used before it has been assigned a value. A null reference exception could result at runtime

Why I'm gettin this kind of error. I have been practising with respect to tutorial but still I get this. how should clear this error. I have started to practice .net. so please guide me
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim std As DataSet1TableAdapters.studentTableAdapter
If txtname.Text = "" Then
lblMessage.Text = "Please enter name"
ElseIf txtclass.Text = "" Then
lblMessage.Text = "Please enter class "
ElseIf txtsemseter.Text = "" Then
lblMessage.Text = "Please enter semester"
Else
std.Insert(Name:=txtname.Text, Class:=txtclass.Text, Semester:=txtsemseter.Text)
End If
End Sub
link of tutorial:http://www.youtube.com/watch?v=wDFo-nGdUQY
do as below
Dim std As New DataSet1TableAdapters.studentTableAdapter()
when you call std.Insert you need to have object of DataSet1TableAdapters.studentTableAdapter
You'll need to new up the variable, as in:
Dim std As New DataSet1TableAdapters.studentTableAdapter()
Edit: I was trying to do this on a phone, not easy :)

Why is my VB.NET website not sending an email?

My code is adding a user to my database. I am trying to have my site send an email with a passcode to verify the email account is legit.
First I am trying to get it to send a basic test email. Then I plan on adding the passcode in a link to my site validating it.
My problem is my code doesn't send the basic test email.
Imports System.Data.SqlClient
Imports System.Net.Mail
Partial Class Account_Register
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
RegisterUser.ContinueDestinationPageUrl = Request.QueryString("ReturnUrl")
End Sub
Protected Sub RegisterUser_CreatedUser(ByVal sender As Object, ByVal e As EventArgs) Handles RegisterUser.CreatedUser
FormsAuthentication.SetAuthCookie(RegisterUser.UserName, False)
Dim MyMailMessage As New MailMessage()
' MyMailMessage.IsBodyHtml = True
MyMailMessage.From = New MailAddress("NAME#gmail.com")
MyMailMessage.To.Add("Name#yahoo.com")
MyMailMessage.Subject = "Email Confirmation"
MyMailMessage.Body = "TESTING"
'MyMailMessage.Body = "<html>" & RegisterUser.UserName & "Link: $" & "<br/> " & "</html>"
'Create the SMTPClient object and specify the SMTP GMail server
Dim SMTPServer As New SmtpClient("smtp.gmail.com")
SMTPServer.Port = 588
SMTPServer.Credentials = New System.Net.NetworkCredential("NAME#gmail.com", "Password")
SMTPServer.EnableSsl = True
Try
SMTPServer.Send(MyMailMessage)
'MessageBox.Show("Email Sent")
Catch ex As SmtpException
'MessageBox.Show(ex.Message)
End Try
Dim continueUrl As String = RegisterUser.ContinueDestinationPageUrl
If String.IsNullOrEmpty(continueUrl) Then
continueUrl = "~/"
End If
Response.Redirect(continueUrl)
End Sub
End Class
Any help?
Change the port number Gmail SMTP port is : 465
Use this
SMTPServer.Port = 465
So I ended up having to use Port = 587
Thank you for the help!

Cannot read cookie from another page in different web application on same domain Asp.Net

When I open a page from another web application on same domain I am trying to read the cookie that was created on the original page, But it I cant read the cookie. If I move that page in to the same web application then it works, but thats not what I want.
[Domain: MyCompany.mobi]
[WebApp A] - create cookie and launch page
Protected Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
Dim aCookie As New HttpCookie("TestCookie")
aCookie.Value = "Hello World"
aCookie.Expires = DateTime.Now.AddDays(1)
Response.Cookies.Add(aCookie)
Dim script = "window.open('http://MyCompany.mobi/webappB/default.aspx?id=TestCookie')"
'open page in WebsiteB
ScriptManager.RegisterStartupScript(Me, Me.GetType, "OpenPage", script, True)
End Sub
[Domain: MyCompany.mobi]
[WebApp B] - read the cookie and display in label
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim id As String = ""
If Request.QueryString("id") IsNot Nothing Then id = Request.QueryString("id").ToString
If Request.Cookies(id) IsNot Nothing Then
Dim aCookie As HttpCookie = Request.Cookies(id)
Label1.Text = aCookie.Name & " : " & aCookie.Value
Else
Label1.Text = "Cannot read cookie"
End If
End Sub
Cookies are associated with domain names; not the physical servers that are pointed to by DNS.
For security reasons, you cannot read cookies from a different domain name.
You need to pass the information in the URL.

Email ASP.NET webpage with Chart Controls

I have an asp.net 4.0 webpage which has 10 chart controls on it. I have been to email the chart controls to the current logged in user when they open the page. The chart controls will be different for each user. I have been testing this by trying to send 1 chart control but the body of the email doesnt show the chart only the image outline. I have tried several things but cant get it to work. The code i have just now is -
web.config
<add key="ChartImageHandler" value="storage=memory;deleteAfterServicing=true;"/>
webpage
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
SendMail()
End Sub
Private Sub SendMail()
Dim SB As New StringBuilder()
Dim SW As New StringWriter(SB)
Dim htmlTW As New HtmlTextWriter(SW)
'SB.Append("<td><img src=""cid:chart17""></td>")
Chart10.RenderControl(htmlTW)
Dim MyHTML As String = SB.ToString()
Dim from As String = "EMAIL ADDRESS"
Dim recip As String = "EMAIL ADDRESS"
'Dim recip As String = Membership.GetUser.Email.ToString
Dim subject As String = "Test Email"
'Create message object and populate w/ data from form
Dim message As System.Net.Mail.MailMessage = New System.Net.Mail.MailMessage()
message.From = New System.Net.Mail.MailAddress(from.Trim())
message.To.Add(recip.Trim())
message.Subject = subject.Trim()
message.IsBodyHtml = True
message.Body = MyHTML
'Setup SmtpClient to send email. Uses web.config settings.
Dim smtpClient As System.Net.Mail.SmtpClient = New System.Net.Mail.SmtpClient()
'Error handling for sending message
Try
smtpClient.Send(message)
'Exception contains information on each failed receipient
Catch recExc As System.Net.Mail.SmtpFailedRecipientsException
For recipient = 0 To recExc.InnerExceptions.Length - 1
Dim statusCode As System.Net.Mail.SmtpStatusCode
'Each InnerException is an System.Net.Mail.SmtpFailed RecipientException
statusCode = recExc.InnerExceptions(recipient).StatusCode
If (statusCode = Net.Mail.SmtpStatusCode.MailboxBusy) Or (statusCode = Net.Mail.SmtpStatusCode.MailboxUnavailable) Then
'Log this to event log: recExc.InnerExceptions(recipient).FailedRecipient
System.Threading.Thread.Sleep(5000)
smtpClient.Send(message)
Else
'Log error to event log.
'recExc.InnerExceptions(recipient).StatusCode or use statusCode
End If
Next
'General SMTP execptions
Catch smtpExc As System.Net.Mail.SmtpException
'Log error to event log using StatusCode information in
'smtpExc.StatusCode
Catch ex As Exception
'Log error to event log.
End Try
End Sub
As you can see i have tried some examples on forums like "SB.Append" and "chart10.rendercontrol(htmlTW) but both do not work for me.
Any helpo would be greatful.
You are not attaching the image to the e-mail.
''I am not sure how to handle memory streams in vb but it should be something like so.
Dim ms as MemoryStream = new MemoryStream()
Chart10.SaveImage(ms, ChartImageFormat.Png)
Dim A As System.Net.Mail.Attachment = New System.Net.Mail.Attachment(ms, "MyChart.png")
A.ContentId = "chart17"
A.ContentDisposition.Inline = True
message.Attachments.Add(A)

Resources