Search code examples
c#emailemail-attachmentsmailkitmimekit

How can I send an email with MimeKit in C#


Hi everyone I'm trying to send an email using the MimeKit but I'm trying to attach a .pdf file I have some problems:

This is how I'm trying to send it:

 private bool EnviarMail(string file, string from, string to, string subject, string content, string name)
    {
        bool estado = false;

        try
        {
            var mensaje = new MimeMessage();
            mensaje.From.Add(new MailboxAddress(name, from));
            mensaje.To.Add(new MailboxAddress("", to));
            mensaje.Subject = subject;

            var bodyBuilder = new BodyBuilder();
            bodyBuilder.HtmlBody = content;
            bodyBuilder.Attachments.Add(file);
            mensaje.Body = bodyBuilder.ToMessageBody();

            using (var client = new SmtpClient("myHost", myPort))
            {
                client.Send(mensaje);    
            }

            estado = true;
            return estado;
        }
        catch (Exception ex)
        {
            return estado;
        }
    }

But I have this error on client.send(mensaje) line. It says:

Argument 1: cannot convert from 'MimeKit.MimeMessage' to ' System.Net.Mail.MailMessage'

How can I send this email correctly?

I tried what is was told here : Can I send files via email using MailKit?

But I couldn't do it for same error


Solution

  • The error indicates that you are using the wrong SMTP client!

    You should be using the one that comes with MimeKit (MailKit.Net.Smtp.SmtpClient) and not the one in .NET (System.Net.Mail.SmtpClient)

    Note that MimeKit and MailKit work hand-in-hand with MimeKit devoted to the parsing and handling of messages. Where as MailKit concerns the network aspects of sending and receiving messages.