Saving MailMessage to Disk (or Database)
Hi,
I have a system where an email is generated and sent out. I need to create a mechanism to store the email as proof that it was sent.
At first I thought I could store the email in my database. Easy until I realised that MailMessage() is not serialised. Did find some links on how to serialise it but it looks enormously complicated and I could not get any of them close to working.
I then came across this article which adds a save method to the class. The code can be found here:
http://www.codeproject.com/KB/IP/smtpclientext.aspx
It’s written in C# so I’ve had to convert it VB.Net but I cannot see to fix a single error which is:
Extension methods can be defined only in modules.
Here is the VB code:
Code:
Imports System.Net.Mail
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Imports System.IO
Imports System.Reflection
Namespace MailMessageExtension
Public NotInheritable Class MailMessageExt
Private Sub New()
End Sub
<System.Runtime.CompilerServices.Extension> _
Public Shared Sub Save(Message As MailMessage, FileName As String)
Dim assembly As Assembly = GetType(SmtpClient).Assembly
Dim _mailWriterType As Type = assembly.[GetType]("System.Net.Mail.MailWriter")
Using _fileStream As New FileStream(FileName, FileMode.Create)
' Get reflection info for MailWriter contructor
Dim _mailWriterContructor As ConstructorInfo = _mailWriterType.GetConstructor(BindingFlags.Instance Or BindingFlags.NonPublic, Nothing, New Type() {GetType(Stream)}, Nothing)
' Construct MailWriter object with our FileStream
Dim _mailWriter As Object = _mailWriterContructor.Invoke(New Object() {_fileStream})
' Get reflection info for Send() method on MailMessage
Dim _sendMethod As MethodInfo = GetType(MailMessage).GetMethod("Send", BindingFlags.Instance Or BindingFlags.NonPublic)
' Call method passing in MailWriter
_sendMethod.Invoke(Message, BindingFlags.Instance Or BindingFlags.NonPublic, Nothing, New Object() {_mailWriter, True}, Nothing)
' Finally get reflection info for Close() method on our MailWriter
Dim _closeMethod As MethodInfo = _mailWriter.[GetType]().GetMethod("Close", BindingFlags.Instance Or BindingFlags.NonPublic)
' Call close method
_closeMethod.Invoke(_mailWriter, BindingFlags.Instance Or BindingFlags.NonPublic, Nothing, New Object() {}, Nothing)
End Using
End Sub
End Class
End Namespace
Any help much appreciated.
Re: Saving MailMessage to Disk (or Database)
Wouldn't it be a whole lot simpler to send the message to whoever it is supposed to go to AND to the mailbox sending it thereby storing a copy of the sent message in the mailbox of the sending account?
I.E., why not just send yourself a copy? Or a Blindcopy?