VB.NET

如何在 vb.net 中发送带有附件的电子邮件

小云
159
2023-09-26 08:40:29
栏目: 编程语言

在 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

在上述代码中,你需要替换以下部分:

通过修改这些参数,你可以在 VB.NET 中发送带有附件的电子邮件。

0
看了该问题的人还看了