在 VB.NET 中,你可以使用 System.Net.Mail
命名空間中的 MailMessage
類來創建和發送帶附件的電子郵件。以下是一個示例代碼,演示如何發送帶有附件的電子郵件:
Imports System.Net
Imports System.Net.Mail
Public Class Form1
Private Sub btnSendEmail_Click(sender As Object, e As EventArgs) Handles btnSendEmail.Click
Try
Dim fromAddress As New MailAddress("your_email@example.com", "Your Name")
Dim toAddress As New MailAddress("recipient@example.com", "Recipient Name")
Dim subject As String = "Email with Attachment"
Dim body As String = "This email contains an attachment."
Dim smtpClient As New SmtpClient()
smtpClient.Host = "smtp.example.com"
smtpClient.Port = 587
smtpClient.EnableSsl = True
smtpClient.UseDefaultCredentials = False
smtpClient.Credentials = New NetworkCredential("your_email@example.com", "your_password")
Dim message As New MailMessage(fromAddress, toAddress)
message.Subject = subject
message.Body = body
' 添加附件
Dim attachment As New Attachment("C:\path\to\attachment.txt")
message.Attachments.Add(attachment)
smtpClient.Send(message)
MessageBox.Show("Email sent successfully.")
Catch ex As Exception
MessageBox.Show("An error occurred: " & ex.Message)
End Try
End Sub
End Class
在上述代碼中,你需要替換以下部分:
"your_email@example.com"
:發送電子郵件的郵箱地址
"Your Name"
:發送者的名字
"recipient@example.com"
:接收電子郵件的郵箱地址
"Recipient Name"
:接收者的名字
"smtp.example.com"
:SMTP 服務器的主機名
587
:SMTP 服務器的端口號
"your_password"
:發送電子郵件的郵箱密碼
"C:\path\to\attachment.txt"
:附件的路徑
通過修改這些參數,你可以在 VB.NET 中發送帶有附件的電子郵件。