在 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 中发送带有附件的电子邮件。