Search code examples
c#emailsmtpattachmentmailkit

Mailkit SMTP error - BareLinefeedsAreIllegal


Remote Server returned '550 5.6.2 SMTPSEND.BareLinefeedsAreIllegal; message contains bare linefeeds, which cannot be sent via DATA'

            var message = new MimeMessage();
            message.From.Add(new MailboxAddress(nameFrom, mailboxFrom));
            message.Subject = Subject;
            message.To.Add(new MailboxAddress(mailboxTo));

            var bodyBuilder = new BodyBuilder();

            var multipart = new Multipart("mixed");

            bodyBuilder.HtmlBody = "Test Body";

            multipart.Add(bodyBuilder.ToMessageBody());


            byte[] bytes = System.IO.File.ReadAllBytes("Test.gif");


            var attachment = new MimePart("binary", "bin")
            {
                ContentObject = new ContentObject(new MemoryStream(bytes), ContentEncoding.Base64),
                ContentDisposition = new ContentDisposition(ContentDisposition.Attachment),
                ContentTransferEncoding = ContentEncoding.Binary,
                FileName = "F2.pdf"
            };

            multipart.Add(attachment);

            message.Body = multipart;


            using (var client = new SmtpClient())
            {
                // For demo-purposes, accept all SSL certificates (in case the server supports STARTTLS)
                client.ServerCertificateValidationCallback = (s, c, h, e) => true;

                client.Connect(ssServer, ssPort, MailKit.Security.SecureSocketOptions.Auto);

                // Note: since we don't have an OAuth2 token, disable
                // the XOAUTH2 authentication mechanism.
                client.AuthenticationMechanisms.Remove("XOAUTH2");

                // Note: only needed if the SMTP server requires authentication
                client.Authenticate(ssMailBox, ssMailBoxPassword);

                client.Send(message);
            }

I have already tried with encoding ContentEncoding.Base64 and ContentEncoding.Binary with same result. When I skip the attachment part the mail is sent correctly. The "Test.gif" is just a random gif I'm uploading.

I have read about CHUNKING or the BDAT command but not really sure about this or how to use it with mailkit ... any suggestions? I'm just trying to send a normal SMTP mail with attachments, this can't be that hard :|


Solution

  • The solution was, as suggested by @Jstedfast to change:

    ContentTransferEncoding = ContentEncoding.Base64
    

    I misunderstood and tried changing the ContentObject enconding.

    Thanks @Jstedfast