user18432
user18432

Reputation: 53

Sending attachment with MailKit in PowerShell doesn't attach

I have a simple script in PowerShell to simply SMTP a PDF attachment. No subject, and no body. The results show the attachment but the email is always received without it. Am I missing something?

$SMTP = [MailKit.Net.Smtp.SmtpClient]::new()
$Message = [MimeKit.MimeMessage]::new()
$Builder = [MimeKit.BodyBuilder]::new()

$Message.From.Add("[email protected]")
$Message.To.Add("[email protected]")
$Builder.Attachments.Add("C:\Users\myname\Path\MyPDF.pdf")

$SMTP.Connect('smtp.xxxx.com', 465, 'SecureSocketOptions.SslOnConnect')
$SMTP.Authenticate($MAILCREDENTIALS)

$SMTP.Send($Message)
$SMTP.Disconnect($true)
$SMTP.Dispose()

Output after sending:

ContentDuration         : 
ContentMd5              :
ContentTransferEncoding : Base64
FileName                : MyPDF.pdf
Content                 : MimeKit.MimeContent
ContentObject           : MimeKit.MimeContent
Headers                 : {Content-Type: application/pdf; name="MyPDF.pdf", Content-Disposition: attachment; filename="MyPDF.pdf", Content-Transfer-Encoding: base64}  
ContentDisposition      : Content-Disposition: attachment; filename="MyPDF.pdf"
ContentType             : Content-Type: application/pdf; name="MyPDF.pdf"
ContentBase             :
ContentLocation         :
ContentId               :
IsAttachment            : True

Upvotes: 0

Views: 1155

Answers (1)

Anders Thyrsson
Anders Thyrsson

Reputation: 67

I would recommend you to look at this project on Github: https://github.com/EvotecIT/Mailozaurr
It is built on top of MimeKit and MailKit.

Regarding your code, try adding this just after "$Builder.Attachments.Add....".

$Message.Body = $Builder.ToMessageBody()

Upvotes: 1

Related Questions