When I try to add an MHTML file as an attachment to an email message in VBScript, the ContentMediaType
is incorrectly set to "message/rfc822"
(RFC 822). From what I understand, this is correct according to Microsoft, but is incorrect according to RFC 2557 which states that it should be "multipart/related"
. This is a problem, because most (if not all) mail clients interpret "message/rfc822"
as an email message. Since the file extensions ".mht"
and ".mhtml"
do not match any valid file extension of an email message, the mail client appends one of ".msg"
, ".eml"
, etc. to the filename. When a user opens the attachment, it opens as an email message and doesn't display correctly since an MHTML file and an email message are saved differently.
Sub SendEmail(FromAddress, ToAddress, Subject, Body, Attachment)
Call Err.Clear
On Error Resume Next
Schema = "http://schemas.microsoft.com/cdo/configuration/"
Set Configuration = Sys.OleObject("CDO.Configuration")
Configuration.Fields.Item(Schema + "sendusing") = 2
Configuration.Fields.Item(Schema + "smtpserver") = SMTPServer
Configuration.Fields.Item(Schema + "smtpserverport") = 25
Configuration.Fields.Item(Schema + "smtpauthenticate") = 1
' Configuration.Fields.Item(schema + "sendusername") = ""
' Configuration.Fields.Item(schema + "sendpassword") = ""
Call Configuration.Fields.Update
Set Message = Sys.OleObject("CDO.Message")
Set Message.Configuration = Configuration
Message.From = FromAddress
Message.To = ToAddress
Message.Subject = Subject
Message.HTMLBody = Body
If Not IsEmpty(Attachment) Then
'CDO.Message.AddAttachment doesn't set the correct content media type for an MHTML file.
Call Message.AddAttachment(Attachment)
End If
Call Message.Send
End Sub
When I run this code, Message.Attachments.Item(1).ContentMediaType
is set to "message/rfc822"
. I need it to be "multipart/related"
if Attachment
(a string) ends with ".mht"
or ".mhtml"
(case-insensitive). I can do this with the following code.
If Len(Attachment) >= 4 And InStr(Len(Attachment) - 3, Attachment, ".mht", vbTextCompare) Or Len(Attachment) >= 4 And InStr(Len(Attachment) - 5, Attachment, ".mhtml", vbTextCompare) Then
Message.Attachments.Item(1).ContentMediaType = "multipart/related"
End If
For some unknown reason, this undefines the attachment from Message.Attachments
.
I've looked at manually adding the attachment per these instructions, but when I call Message.Attachments.Item(1).Fields.Update
, the object becomes undefined. I think setting the attachments's ContentMediaType
, implicitly invokes it's Fields
's Update
method which is what I think is responsible for this unexpected behavior.
How can I get around this and send an MHTML file with the "multipart/related"
content type while maintaining the proper file extension?