Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / desktop / Win32

Sending an Email to Yourself

2.18/5 (13 votes)
21 Oct 2015CPOL1 min read 14.8K  
Code to include in a deployment project

Introduction

Why do you need code to send an email to yourself you might ask?
Good question!

One of my deployed programs extracts information on the user's computer. The user needs to type in that information to buy a product on my website. They can either write it down and risk transcription errors or, more safely, send it to themselves in an email.

I searched all over for a solution. It seemed to require the complexities of EWS and I couldn't be asked to wade through all that bloat. "Beautiful code is Simple code".

This piece of code asks them to enter their email address in an input box and thereafter sends the email so transcription errors can't arise.

The code doesn't require great understanding. It works in all versions of Windows from XP and Framework4 upwards. Probably it works in lower Frameworks but I haven't tested that.

The Code

VB.NET
Imports System.Net.Mail 

Private Function SendYourselfAnEmail()

Dim UserEmail = InputBox("Enter your own email address",_
"Send yourself --- whatever you want them to send to themselves --- )
Dim address As New MailAddress(UserEmail)
Dim host = "smtp." & address.Host

Try
   Dim from = UserEmail
   Dim too = UserEmail
   Dim subject = "---whatever it is---"
   Dim body ="---whatever it is---"
   '//set the server
     Dim smtp As New SmtpClient(host)
   '//send mail
   smtp.Send(New MailMessage(from, too, subject, body))
   MsgBox("Your Email has been sent successfully - Thank You")
Catch ex As Exception
   MsgBox("Your email has not been sent " & ex.ToString)
End Try

End Function

Points of Interest

I have put the code in a function but it can be included in-line in any other function - except of course for the Imports statement which must be placed outside any class.

In the 'dim host ...' line, take care to put the period after smtp like this - "smtp." - otherwise it won't work. It's easy to miss.

You might want to point out in the InputBox that if the user enters their own email address incorrectly then their server might not bounce it. Not all servers report a bounce.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)