Go to Gmail Security Settings and Turn On Less Secure App Access

The Gmail you want to send from cannot be Two-Factor Authorized.


Then Write the following Code for sending an email using Gmail With Attachments.

using System;

using System.Net;

using System.Net.Mail;

 

namespace TestInterfaceDemo

{

    class Program

    {

        static void Main(string[] args)

        {

            var fromMail = "the gmail you want to sent from";

            var to = "the gmail you want to sent to";

            var subject = "The mail subject";

            var body = "The mail body";

            var path = "File path (ex. D://test.txt)";

            var password = "From mail password";

 

            Attachment attach = new Attachment(path);

            MailMessage msg = new MailMessage();

 

            msg.From = new MailAddress(fromMail);

            msg.To.Add(to);

            msg.Subject = subject;

            msg.Body = body;

            msg.Attachments.Add(attach);

 

            SmtpClient smtp = new SmtpClient();

            smtp.Host = "smtp.gmail.com";

            NetworkCredential credential = new NetworkCredential();

            credential.UserName = fromMail;

            credential.Password = password;

            smtp.Credentials = credential;

            smtp.EnableSsl = true;

            smtp.Port = 587;

            smtp.Send(msg);

 

            Console.ReadKey();

        }

    }

}

 

The mail will look like this after received!



Post a Comment

Previous Post Next Post