Home > database >  Send emails with attachments via c #
Send emails with attachments via c #

Time:05-14

I would like to send an email with attachments via C #, I tried with the following code which is compiled but then once I start the program I receive what is reported in the screenshot and the email is not sent, can anyone help me?

using System.Net;
using System.Net.Mail;

static void email_send()
{
    MailMessage mail = new MailMessage();
    SmtpClient SmtpServer = new SmtpClient("smtpservername");
    mail.From = new MailAddress("sendingemail");
    mail.To.Add("emailrecipients");
    mail.Subject = "Test email";
    mail.Body = "mail with attachment";

    System.Net.Mail.Attachment attachment;
    attachment = new System.Net.Mail.Attachment("D:/attachment.txt");
    mail.Attachments.Add(attachment);

    SmtpServer.Port = 25;
    SmtpServer.Credentials = new System.Net.NetworkCredential("sendingemail", "sendingemailpassword");
    SmtpServer.EnableSsl = false;

    SmtpServer.Send(mail);

}
email_send();

enter image description here

CodePudding user response:

Based on the documentation for how you're creating your attachment, you are just appending the string "D:/attachment.txt" to the email rather than the file itself.

In order to send the file as an attachment, you want to use the Attachment(Stream stream, string? name) constructor for your attachment.

Before you tried sending the attachment, did you verify that the credentials and SMTP server you have setup all work?

CodePudding user response:

Based on the error you're getting it sounds like it's a configuration issue, not an issue with there being an attachment.

Have you tried with SslEnabled = true?

To test whether the credentials are the issue, you could try making the request locally using: SmtpServer.UseDefaultCredentials = true

Another thing worth pointing out is that I'd recommend utilising a using block for your SmtpServer variable, as this will handle disposing any resources, especially if you try adding an attachment as a memory stream.

  • Related