Sending an email in VB 2005

  • Thread starter Thread starter si_owen
  • Start date Start date
S

si_owen

Hi Guys,

I have been trying to update my existing email routine within my .net
v2 web app website, I currently have the following code:

Dim GroupMailSender As New
SmtpClient(ConfigurationManager.AppSettings("Mail.SMTP"))

Dim GroupFrom As MailAddress = New MailAddress("(e-mail address removed)")
Dim GroupTo As MailAddress = New MailAddress("(e-mail address removed)")
Dim GroupEmail As MailMessage = New MailMessage(GroupFrom,
GroupTo)

GroupEmail.Subject = txtGroupSubject.Text
GroupEmail.Body = txtGroupMessage.Text

Try
GroupMailSender.Send(GroupEmail)
Catch ex As Exception
txtGroupMessage.Text &= ex.ToString
End Try

lblGroupFeedback.Text = "Mail Message Has Been Sent"

clearGroupPanel()

This code works fine, although I am trying to change the from address
to recognise the user currently using the system. The code below picks
up the users identity and retrieves their email from the database:

Dim user As New UserEntity
Session("UserEmail") = user.Email

However the problem is when I have attempted to use this variable
rather than a fixed email address, for example (code replacement):

Dim user As New UserEntity
Session("UserEmail") = user.Email

dim testEmail as string = Session("UserEmail")

Dim GroupFrom As MailAddress = New MailAddress(testEmail)

However I get the following error, " Unable to cast object of type
'System.String' to type 'System.Net.Mail.MailAddress'.".

I have also tried changing the variable type from a string to a
system.net.mail.mailmessage, but i still encounter the same error.

Has anyone encountered and overcome this problem?? Any help would be
very much appreciated.

Thanks,

Simon
 
This is how I do it and it works just fine:

Dim body as string = "Whatever"

Dim subject as string = "Subject"

Dim fromAddress As New System.Net.Mail.MailAddress(fromAddy)

Dim toAddress As New System.Net.Mail.MailAddress(toAddy)

Dim msg As New System.Net.Mail.MailMessage

msg.From = fromAddress

msg.To.Add(toAddress)

msg.CC.Add(ccAddress)

msg.Subject = Subject

msg.Body = body

msg.IsBodyHtml = True

Dim mailSender As New System.Net.Mail.SmtpClient()

mailSender.Host = "myhost.com"

mailSender.Send(msg)

Hope it helps...
 
Back
Top