0

我在这个问题上搜索了几天,并在这个网站和其他网站上引用了许多问题,但都无济于事。除了这个,我还有其他所有功能都在工作。我还参考了 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

我有公开和共享的电子邮件,因此附件表格可以引用它。

非常感谢任何帮助。提前致谢。

4

1 回答 1

1

我想您调用循环以在发送电子邮件的代码之前添加附件。如果是这种情况,那么您再次重新初始化变量 email 并且您丢失了以前的附件

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
于 2013-07-13T20:02:42.390 回答