我已经在这个问题上搜索了几天,并在本网站和其他网站上引用了很多问题,但都无济于事。我有其他所有功能,除此之外。我还引用了Visual Studio中出现的工具提示,但似乎没有任何效果。我的代码不会生成错误,但电子邮件也没有附件。这是我的一段代码,可用作参考。
'Add Attachments from alist array'
If alist.Count > 1 Then
For x As Integer = 1 To alist.Count - 1
Quick_Mail.email.Attachments.Add(New System.Net.Mail.Attachment(alist(x).ToString))
Next
End If
我有这种方式,因为我有一个单独的表单添加附件。附件的路径存储为alist数组中的字符串。每次添加新附件时,都会保留alist。这会导致第一个位置为空,这就是我将x初始化为1的原因。
以下是我的电子邮件设置其余部分的代码
Public Shared email As New MailMessage()
Dim smtp As SmtpClient = New SmtpClient
smtp.Credentials = New Net.NetworkCredential(user, pass)
smtp.Host = host
smtp.Port = port
smtp.EnableSsl = False
email = New MailMessage()
email.From = New MailAddress(user)
email.To = txt_to.text
email.CC = txt_cc.text
email.BCC = txt_bcc.text
email.Subject = txt_subject.Text
email.Body = txt_message.Text
我的电子邮件是公开的和共享的,因此附件表单可以引用它。
非常感谢任何帮助。提前谢谢。
答案 0 :(得分:0)
我想你调用循环在代码发送电子邮件之前添加附件。如果是这种情况,那么您再次重新初始化变量电子邮件,并丢失以前的附件
Public Shared email As New MailMessage()
Dim smtp As SmtpClient = New SmtpClient
smtp.Credentials = New Net.NetworkCredential(user, pass)
smtp.Host = host
smtp.Port = port
smtp.EnableSsl = False
' THIS LINE REINITIALIZE THE EMAIL AND KILLS THE ATTACHMENTS
' email = New MailMessage()
email.From = New MailAddress(user)
email.To = txt_to.text
email.CC = txt_cc.text
email.BCC = txt_bcc.text
email.Subject = txt_subject.Text
email.Body = txt_message.Text
但是,为这类问题保留共享变量将始终是一个问题。为什么不在sub中隔离此代码并将附件列表传递给此sub,以避免公开Shared变量?
Public Sub SendMail(alist as List(Of String))
Dim email = New MailMessage()
Dim smtp = New SmtpClient()
For x As Integer = 1 To alist.Count - 1
email.Attachments.Add(New Attachment(alist(x).ToString))
Next
smtp.Credentials = New Net.NetworkCredential(user, pass)
smtp.Host = host
smtp.Port = port
smtp.EnableSsl = False
email.From = New MailAddress(user)
email.To = txt_to.text
email.CC = txt_cc.text
email.BCC = txt_bcc.text
email.Subject = txt_subject.Text
email.Body = txt_message.Text
smtp.Send(email)
End Sub