发送电子邮件 - VB.Net - Windows窗体

时间:2016-03-10 22:24:06

标签: vb.net email

我尝试了不同的端口号,但我不断收到错误消息,也没有发送电子邮件。我的目标是能够成功发送电子邮件,并且邮件将包含预订的约会的详细信息。有什么帮助吗?

    Dim UserName As String = "example@gmail.com"
    Dim mail As MailMessage = New MailMessage

    mail.From = New MailAddress(UserName)
    mail.To.Add(New MailAddress(txtEmailAddress.Text))
    mail.Subject = "Appointment Details"
    mail.Body = "Test message"

    mail.IsBodyHtml = True

    Dim client As SmtpClient = New SmtpClient("smtp.gmail.com", 465)
    client.EnableSsl = True
    client.Credentials = New System.Net.NetworkCredential(UserName, "***")
    Try
        client.Send(mail)
    Catch ex As Exception
        MessageBox.Show("Sending email failed. Please Try again")
    End Try

2 个答案:

答案 0 :(得分:0)

您需要做的是添加client.UseDefaultCredentials = False,但请确保在调用client.Credentials = New System.Net.NetworkCredential(UserName, "***")之前将其设置为false

此外,对于GMail,您需要使用端口587,它是支持STARTTLS扩展的端口(这是System.Net.Mail.SmtpClient支持SSL的唯一方式。)

换句话说,将代码更改为:

Dim UserName As String = "example@gmail.com"
Dim mail As MailMessage = New MailMessage

mail.From = New MailAddress(UserName)
mail.To.Add(New MailAddress(txtEmailAddress.Text))
mail.Subject = "Appointment Details"
mail.Body = "Test message"

mail.IsBodyHtml = True

Dim client As SmtpClient = New SmtpClient("smtp.gmail.com", 587)
client.EnableSsl = True
client.UseDefaultCredentials = False
client.Credentials = New System.Net.NetworkCredential(UserName, "***")
Try
    client.Send(mail)
Catch ex As Exception
    MessageBox.Show("Sending email failed. Please Try again")
End Try

答案 1 :(得分:0)

试试这个,

转到您的Gmail帐户(www.gmail.com) 登录,并检查您是否“为所有邮件启用了Pop”。 你可以在“转发和POP / IMAP”标签下找到这个

同时尝试将端口号切换为587