如何在System.Net.Mail中使用标签文本作为To地址

时间:2014-01-10 14:27:38

标签: xml vb.net

我有一个使用System.Net.Mail发送电子邮件的VB.net程序。我想发送一封电子邮件到“Label1”中显示的文本我正在拉电子邮件并将其分配给标签......我有:

mail.To.Add(Me.Label1.Text) 'Sets the "To" address

然而,这不起作用。如何将label1.text分配给mail.To.Add?看起来在发送电子邮件之前没有分配它。也许我需要以不同的方式从xml文件中提取?

Dim document As XmlReader = New XmlTextReader("C:\xml.xml")

            'loop through the xml file
            While (document.Read())

                Dim type = document.NodeType

                'if node type was element
                If (type = XmlNodeType.Element) Then

                    'if the loop found a <Site> tag
                    If (document.Name = "Site") Then

                        Me.Text = document.ReadInnerXml.ToString()

                    End If
                    'if the loop found a <Path> tag
                    If (document.Name = "Email") Then

                        Me.Label1.Text = document.ReadInnerXml.ToString()
                        Email = Me.Label1.Text
                        MsgBox("this is done")
                    End If


                End If

            End While

        Else

            MessageBox.Show("The filename you selected was not found.  ")
            Me.Close()
        End If

Try

            'Lets Send the Mail
            SmtpServer.Credentials = New  _
            Net.NetworkCredential("""") 'Assign the network credentials
            SmtpServer.Port = 25 'Assign the SMTP Port
            SmtpServer.Host = "10.0.0.0." 'Assign the Server IP
            mail = New MailMessage() 'Starts a mail message
            mail.From = New MailAddress("email") 'Sets the "FROM" address
            mail.To.Add(Me.Label1.Text) 'Sets the "To" address
            mail.CC.Add("") 'Sets the "CC" address
            mail.Subject = "Break Exception Report " & TodayDt & " - " & TodayEnd
            mail.IsBodyHtml = True
            mail.Body = time.ToString() 'this is to add another chart  You would use a seperate dataset obviously
            SmtpServer.Send(mail)
            MsgBox("mail send1")

        Catch ex As Exception
            MsgBox("error")
        End Try

4 个答案:

答案 0 :(得分:3)

mail.To.Add(new MailAddress(Me.Label1.Text))

答案 1 :(得分:1)

试试这个:

MailMessage message = new MailMessage();
MailAddress to = new MailAddress(this.Label1.Text);
message.To.Add(to);

答案 2 :(得分:1)

我发现你的问题与Label1.Text无关。错误是这一行:

mail.CC.Add("") 'Sets the "CC" address

您无法在CC集合中添加空地址。所以删除它。

答案 3 :(得分:0)

您应该使用SmtpClient类。试试吧:

Dim sm As New SmtpClient(host, port) 'Host e.g. smtp.gmail.com, port usually 25 (non-SSL) or 587 (SSL)

Dim maFrom As MailAddress = New MailAddress(LogInEmail)
Dim maTo As MailAddress = New MailAddress(Label1.Text)
Dim mMsg As New MailMessage(maFrom, maTo)
mMsg.Subject = Topic
mMsg.Body = Message
sm.Send(mMsg)

您可能必须为SMTP客户端启用SSL,具体取决于您的电子邮件提供商设置。