sending an email with attachment in .net core console application

Anjali Agarwal 1,386 Reputation points
2023-05-03T19:01:31.5566667+00:00

I need to send an email with attachment in .net core console application. The part of sending an email is working. The attachment part is not working. I have this code:

public void sendEmail(List<string> toList)

    {

        string from = "test@test.com";

        string UserName = ConfigurationManager.AppSettings["UserName"].ToString();

        string password = ConfigurationManager.AppSettings["password"].ToString();

        string PathToAttachment = ConfigurationManager.AppSettings["AttachPath"].ToString();

       

        foreach (var item in toList)

        {

            using (MailMessage mm = new MailMessage())

            {

                mm.From = new MailAddress(from);

                mm.To.Add(new MailAddress("anjali@test.com"));

                Attachment attachment = new Attachment(PathToAttachment);

                mm.Attachments.Add(attachment);

                mm.Subject = "this is test";

                mm.Body = GetEmailBody();

                mm.IsBodyHtml = true;

                SmtpClient client = new SmtpClient();

                client.Credentials = new NetworkCredential(UserName, password);

                client.Port = 200;

                client.EnableSsl = true;

                client.Host = "smtp.office365.com";

                client.DeliveryMethod = SmtpDeliveryMethod.Network;

                client.Send(mm);

            }

        }

    }

pathToAttachment is: C:\NotificationService\Attachments

The file that needs to be attached is stored inside the application in a folder called attachment. below is the structure:

User's image

NotificationService is the project name and I need to attach test.pdf file in an email attachment. I am getting an error saying:

User's image

Please let me know how can I send an attachment in .net core console application.

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,246 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,404 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Mohammad Nedariya 0 Reputation points
    2024-05-15T12:46:38.93+00:00

    can you please share me your repository for the above project

    0 comments No comments