如何从visual basic 2010专业发送邮件

问题描述:

Imports System.Net
导入System.Net.Mail

Imports System.Net Imports System.Net.Mail

公共类Form1

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    MsgBox("This will send a mail...")
    Try

        Dim smtpserver As New SmtpClient()
        Dim mail As New MailMessage()
        smtpserver.Credentials = New Net.NetworkCredential("myname@gmail.com", "password")
        smtpserver.Port = 465
        smtpserver.Host = "smtp.gmail.com"
        mail = New MailMessage()
        mail.From = New MailAddress("myname@gmail.com")
        mail.To.Add("to mail id")
        mail.Subject = "Test by bharat"
        mail.Body = "hello ooooooooooooooooooooooo"
        smtpserver.Send(mail)
        MsgBox("Mail Sent")
    Catch ex As Exception
        MsgBox(ex.ToString)
        Close()
    End Try


End Sub

结束类

您可以制作一个名为邮件的新类。
如果你做一个课,你不需要再次输入所有的代码,如果你想发送多个电子邮件。

You can make a new class called 'Mail'. If you make a class, you don't have to type all of the code again if you want to send more than 1 email.

Imports System.Net.Mail
Public NotInheritable Class Mail
    Public Property subject As String
    Public Property body As String
    Public Property receiver As String

    Public Sub send()
        Try
            Dim smtpServer As New SmtpClient()
            Dim mail As New MailMessage()
            smtpServer.UseDefaultCredentials = False
            smtpServer.Credentials = New Net.NetworkCredential("yener.turkeli@v-basic.net", "password"))
            smtpServer.Port = 587
            smtpServer.EnableSsl = True
            smtpServer.Host = "smtp.gmail.com"

            mail = New MailMessage()
            mail.From = New MailAddress("yener.turkeli@v-basic.net")
            mail.To.Add(receiver)
            mail.Subject = subject
            mail.Body = body
            smtpServer.Send(mail)
        Catch ex As Exception
            MsgBox(ex.Message & vbNewLine & ex.StackTrace)
        End Try

    End Sub
End Class

然后,您可以在代码中创建一个新对象,您希望在何时发送电子邮件:

And then you can make a new object in your code where and when you want to send the email:

Dim email as new Mail
email.receiver = "receiver@example.com"
email.subject = "Subject"
email.body = "Message"
email.send()