Resolved: Adding attachments using url in mail with C sharp


I can send attachments with URLs, But, looking for support to send a file with an attachment. that too should download from url and attach with mail.
MailMessage mail = new MailMessage();
mail.From = new MailAddress("");

//to mail address

//Add the Attachment

//set the content 
mail.Subject = txtSubject.Text;
mail.Body = "Kindly find the below attachments with the link,";

//send the message 
SmtpClient smtp = new SmtpClient("*****.********.net");

NetworkCredential Credentials = new NetworkCredential("", "********");
smtp.Credentials = Credentials;
Here I’m sending mail with URL as a file, But I want to attach a file instead of sending a link
The sample URL was added as an image link.. But I wanted to add a pdf link.. In this case, I want to download a file and attach it with mail,


I use it mostly in my all projects it’s working fine. its with base 64
First, make sure your Gmail account is turned on for sending emails.
    public static async Task SendEmail(string toUser, string subject, string body
        , string username, string password, string port, string smtpServer, string ccUsers = "", string base64Url = "")
        var toAddress = new System.Net.Mail.MailAddress(toUser, toUser);

        System.Net.Mail.MailMessage emessage = new System.Net.Mail.MailMessage();


        if (!string.IsNullOrEmpty(ccUsers))
            string[] ccIds = ccUsers.Split(',');
            foreach (string item in ccIds)
                emessage.CC.Add(new System.Net.Mail.MailAddress(item));

        emessage.Subject = subject;
        emessage.From = new System.Net.Mail.MailAddress(username);
        emessage.Body = body;
        emessage.IsBodyHtml = true;
        System.Net.Mail.SmtpClient sc = new System.Net.Mail.SmtpClient();

        if (!string.IsNullOrEmpty(base64Url))
            base64Url = base64Url.Replace("data:image/jpeg;base64,", "");
            var imageBytes = Convert.FromBase64String(base64Url);
            var stream = new MemoryStream(imageBytes);
            System.Net.Mime.ContentType ct = new System.Net.Mime.ContentType(System.Net.Mime.MediaTypeNames.Image.Jpeg);
            System.Net.Mail.Attachment at = new System.Net.Mail.Attachment(stream, ct);
            at.ContentDisposition.FileName = "Invoice.jpeg";

        var netCredential = new System.Net.NetworkCredential(username, password);
        sc.Host = smtpServer;
        sc.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
        sc.UseDefaultCredentials = false;
        sc.Credentials = netCredential;
        sc.EnableSsl = true;
        sc.Port = Convert.ToInt32(port);
        await sc.SendMailAsync(emessage);


If you have better answer, please add a comment about this, thank you!