需要帮助找出如何在VB.NET中添加电子邮件附件

时间:2014-09-30 04:33:41

标签: vb.net

我正在努力弄清楚如何在VB.NET中添加附件到电子邮件。这是我的代码到目前为止,我不知道如何包含附件。这是我第一次使用命令提示符和电子邮件系统。

    Imports System.Net.Mail

模块模块1

Sub Main()
    Dim client As New SmtpClient
    Dim email As New MailMessage
    Dim seconds As Integer
    Dim interval As Integer
    Dim ip As String = 0
    Dim counter As Integer
    Dim desktop As String = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
    input(seconds, interval, ip, counter)
    ping(interval, ip, desktop, counter)
    Console.WriteLine("Program successfully executed.")
    Console.ReadLine()

End Sub
Sub input(ByRef seconds As Integer, ByRef interval As Integer, ByRef ip As String, ByRef counter As Integer)
    Console.WriteLine("Please enter the amount of seconds you would like between pings.")
    Console.WriteLine("Please enter no fewer than five seconds.")
    seconds = Console.ReadLine()
    Console.Clear()
    interval = seconds * 1000
    Console.WriteLine("Please enter the IP you will be pinging.")
    ip = Console.ReadLine()
    Console.Clear()
    Console.WriteLine("How many times would you like to ping?")
    counter = Console.ReadLine()
    Console.Clear()
End Sub
Sub ping(ByVal interval As Integer, ByVal ip As String, ByVal desktop As String, ByRef counter As Integer)
    Do Until counter = 0
        Process.Start("CMD", "/c ping " & ip & " >> " & desktop & "\log.txt")
        System.Threading.Thread.Sleep(interval)
        counter = counter - 1
    Loop
End Sub
Sub email(ByRef client As SmtpClient, ByRef email As MailMessage, ByVal desktop As String)
    client.UseDefaultCredentials = False
    client.Credentials = New Net.NetworkCredential("fakebusiness01@gmail.com", "*****")
    client.Port = 587
    client.EnableSsl = True
    client.Host = "smtp.gmail.com"
    email = New MailMessage()
    email.From = New MailAddress("fakebusiness01@gmail.com")
    email.To.Add("genericmail01@gmail.com")
    email.Subject = "Ping Results"
    email.IsBodyHtml = False
    email.Body = "The pings were successful, attached is the ping log."

    client.Send(email)
End Sub

结束模块

1 个答案:

答案 0 :(得分:2)

您的Attachments对象中已有属性MailMessage。您只需要检查要附加的文件是否存在以避免任何异常,如下所示;

 Dim sFile as String = "Full_File_Path"
 Dim Attachment = New System.Net.Mail.Attachment(sFile)

  If IO.File.Exists(sFile) Then _
    email.Attachments.Add(Attachment)

如果您要附加多个文件;

' Assuming AttachmentFiles is an ArrayList holding your files
Dim iCountFiles as integer

 If AttachmentFiles IsNot Nothing Then

    iCountFiles  = AttachmentFiles.Count - 1

    For index = 0 To iCountFiles 

        Dim Attachment = New System.Net.Mail.Attachment(AttachmentFiles(index))

        If IO.File.Exists(AttachmentFiles(index)) Then _
          email.Attachments.Add(Attachment)
    Next

  End If