如何在发送带附件的电子邮件之前将文件附加到临时位置?

时间:2013-02-11 13:53:41

标签: vb.net winforms email-attachments

在按下我的提交按钮然后发送带有附件的电子邮件之前,我在将所选文件附加到我的VB.net表单时遇到了一些麻烦。 目前,我的表单可以打开一个对话框来浏览文件,但是从我机器上的某个位置选择文件后我收到错误。 有人可以帮忙吗?谢谢。 这是我用于附件按钮的代码:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim openDLG As New OpenFileDialog

    'openDLG.AddExtension = True
    openDLG.ReadOnlyChecked = True
    openDLG.Multiselect = True
    openDLG.Title = "Select the file(s) you want added to the message..."
    openDLG.Filter = "All Files (*.*)|*.*"

    If openDLG.ShowDialog = Windows.Forms.DialogResult.OK Then

        For Each item As String In openDLG.FileNames

            'Create a new System.NET.Mail.Attachment class instance for each file.
            attachToMsg = New System.Net.Mail.Attachment(item)

            'Then add the attachment to your message. You have to do this everytime you run the code
            'above.

            EmailMessage.Attachments.Add(attachToMsg)

        Next

        MsgBox("I have finished adding all of the selected files! You can do more if you want!")

    End If
End Sub

Button3代码:

Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
    Using message As New MailMessage()
        'set to the from, to and subject fields
        message.From = (New MailAddress(TextBox3.Text.ToString()))
        message.[To].Add(New MailAddress("NO.ONE@elsewhere.com"))
        message.Subject = "New commission query"

        'code the message body
        Dim MsgBody As String
        MsgBody = TextBox1.Text.ToString() & vbCr & _
                  TextBox2.Text.ToString() & vbCr & _
                  TextBox3.Text.ToString() & vbCr & _
                  ComboBox1.Text.ToString() & vbCr & _
                  ComboBox2.Text.ToString() & vbCr & _
                  ComboBox3.Text.ToString() & vbCr & _
                  ComboBox4.Text.ToString() & vbCr
        message.Body = MsgBody
        Dim client As New SmtpClient()
        client.Host = "mailhost"
        client.Send(message)
    End Using
        'display submitted box
        MessageBox.Show("Your request has been submitted!", "Congratulations!")
        'close form
        Me.Close()
  End Sub

2 个答案:

答案 0 :(得分:0)

Button3_Click代码中的“message”对象和Button1_Click代码中的“EmailMessage”应该是相同的“message”对象。

正如史蒂夫上面提到的那样......

  

您在哪里定义和初始化了EmailMessage变量?使用调试器并在尝试添加附件时检查该变量是否为Nothing - Steve 5小时前

这是你在哪里定义了EmailMessage对象的情况吗?

也许您应该在FORM Level范围内声明您的EmailMessage对象,然后修改您的Button3代码以访问相同的EmailMessage而不是在附件过程(Button1_Click代码)中,您还需要在实例化之前“实例化”您的EmailMessage消息对象试图修改其属性。

所以你会有类似的东西......

'Declarations section (form scope)

Dim TheEmailMessage As New MailMessage()


Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

Dim openDLG As New OpenFileDialog

  'openDLG.AddExtension = True
  openDLG.ReadOnlyChecked = True
  openDLG.Multiselect = True
  openDLG.Title = "Select the file(s) you want added to the message..."
  openDLG.Filter = "All Files (*.*)|*.*"
  If openDLG.ShowDialog = Windows.Forms.DialogResult.OK Then
    For Each item As String In openDLG.FileNames
      'Create a new System.NET.Mail.Attachment class instance for each file.
      attachToMsg = New System.Net.Mail.Attachment(item)
      'Then add the attachment to your message. 
      'You have to do this everytime you run the code above
      TheEmailMessage.Attachments.Add(attachToMsg)
    Next
    MsgBox("I have finished adding all of the selected files! You can do more if you want!")
  End If
End Sub


Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
  Using TheEmailMessage

    'set to the from, to and subject fields
    TheEmailMessage.From = (New MailAddress(TextBox3.Text.ToString()))
    TheEmailMessage.[To].Add(New MailAddress("NO.ONE@elsewhere.com"))
    TheEmailMessage.Subject = "New commission query"

    'code the message body
    Dim MsgBody As String
    MsgBody = TextBox1.Text.ToString() & vbCr & _
      TextBox2.Text.ToString() & vbCr & _
      TextBox3.Text.ToString() & vbCr & _
      ComboBox1.Text.ToString() & vbCr & _
      ComboBox2.Text.ToString() & vbCr & _
      ComboBox3.Text.ToString() & vbCr & _
      ComboBox4.Text.ToString() & vbCr
    TheEmailMessage.Body = MsgBody
    Dim client As New SmtpClient()
    client.Host = "mailhost"
    client.Send(message)
  End Using
  'display submitted box
  MessageBox.Show("Your request has been submitted!", "Congratulations!")
  'close form
  Me.Close()
End Sub

答案 1 :(得分:0)

将其放入临时文件(文件夹)中。下面是一个从资源中提取文件,放入临时文件并打开它的示例。返回使用的临时文件夹。

 Public Overloads Function EXTRACT_FILE_FROM_RESOURCE(ByVal sFile As String, Optional ByVal andStart As Boolean = True) As String

        Dim assembly As System.Reflection.Assembly = System.Reflection.Assembly.GetExecutingAssembly()
        Dim root As String = assembly.GetName().Name
        Dim stream As System.IO.Stream = assembly.GetManifestResourceStream(root & "." & sFile)
        Dim buffer(Convert.ToInt32(stream.Length) - 1) As Byte
        stream.Read(buffer, 0, buffer.Length)
        stream.Close()
        Dim sFolderUsed As String = GetTempDirectory()
        Dim sFilePath As String

        sFilePath = IO.Path.Combine(sFolderUsed , sFile )


        Using f As New IO.FileStream(sFilePath , IO.FileMode.Create, IO.FileAccess.Write)
            f.Write(buffer, 0, buffer.Length)
            f.Close()
            File.SetAttributes(sFilePath , File.GetAttributes(sFilePath ) And Not FileAttributes.ReadOnly)
        End Using

        If andStart Then
            StartProcess(sFilePath )
        End If
        Return sFolderUsed 


    End Function


    Public Function GetTempDirectory() As String
        Dim pathx As String
        Do
            pathx = IO.Path.Combine(IO.Path.GetTempPath(), IO.Path.GetRandomFileName())
        Loop Until Not Directory.Exists(pathx)
        Directory.CreateDirectory(pathx)
        Return pathx

    End Function