Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specify .eml file name using System.Net.Mail.MailAddress or other library

Tags:

c#

vb.net

I need to file an email when requested.

My code below works:

  • Sends email
  • Files the email when requested
  • But does not allow me to specify the file name (uses a guid as file name)
  • Example: c:\Archive\email\1003d05d-11ca-45e2-a5f4-cf2da29c39d9.eml

Potential Solutions:

  1. Save the file to a temporary folder, rename file, and then copy to final destination
  2. Save the file using another method, better performance

Pros and Cons

  • Solution 1: is ugly and has bad performance

Question

Does anyone know how to file an email to "MySpecifiedFileName.eml", without having to rename and then copy?

Existing Code:

Public Shared Sub Send(ByVal EmailFrom As String, ByVal EmailTo As String, ByVal Subject As String, ByVal HTMLBody As String, Optional SaveToFile As Boolean = False, Optional SaveFilepath As String = "")
    Dim MyMsg As MailMessage = New MailMessage

    Dim Recipients() As String
    Recipients = Split(EmailTo, ";")

    With MyMsg
        .From = New System.Net.Mail.MailAddress(EmailFrom)
        For i = 0 To Recipients.Count - 1
            If Recipients(i).ToString <> "" Then
                .To.Add(New System.Net.Mail.MailAddress(Recipients(i)))
            End If
        Next
        .Sender = New System.Net.Mail.MailAddress(EmailFrom)
        .Subject = Subject
        .Body = HTMLBody
        .BodyEncoding = System.Text.Encoding.UTF8
        .IsBodyHtml = True
        .Priority = MailPriority.High            
    End With

    Dim SmtpServer As New SmtpClient(My.Settings("SMTPServer"))
    SmtpServer.Send(MyMsg)

    REM
    REM Save Email when requested
    REM
    If SaveToFile = True Then
        Dim client As New SmtpClient(My.Settings("SMTPServer"))
        client.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory
        client.PickupDirectoryLocation = SaveFilepath
        client.Send(MyMsg)
        client = Nothing
    End If
    MyMsg = Nothing
    SmtpServer = Nothing
End Sub
like image 601
Internet Engineer Avatar asked May 01 '15 13:05

Internet Engineer


1 Answers

Allan Eagle over at CodeProject.com has created an extension of the System.Net.Mail.MailMessage class that includes the ability to save an email with a specific file name. I believe this will address the issue you raised.

like image 79
ChicagoMike Avatar answered Sep 19 '22 13:09

ChicagoMike