How to send email with attachment in c#

private void SendMailWithoutPortalFieldsInformation(List<string> toList, string fromAddress, string fromTitle, string subject, string portalId, string messageBodyText, string filename, string filemimetype, string filesource)
        {
            MailMessage mailMessage = new MailMessage();
            mailMessage.From = new MailAddress(fromAddress, fromTitle);

            foreach (var item in toList)
            {
                mailMessage.To.Add(new MailAddress(item));
            }

            mailMessage.Subject = subject;
            mailMessage.IsBodyHtml = true;
            mailMessage.Body = messageBodyText;

            SmtpClient smtpClient = new SmtpClient();
            smtpClient.UseDefaultCredentials = false;

            smtpClient.Host = "smtp.domain.com";
            smtpClient.Port = 123; //Port number
            smtpClient.EnableSsl = true;
            smtpClient.Credentials = new System.Net.NetworkCredential("userame", "password");

            if (!string.IsNullOrEmpty(filename) && !string.IsNullOrEmpty(filemimetype) && !string.IsNullOrEmpty(filesource))
            {
                var fileData = filesource.Replace("data:" + filemimetype + ";base64,", "");
                byte[] bytes = Convert.FromBase64String(fileData);
                Stream stream = new MemoryStream(bytes);
                mailMessage.Attachments.Add(new System.Net.Mail.Attachment(stream, filename, filemimetype));
            }

            smtpClient.Send(mailMessage);
        }
Advertisements

#c, #email, #email-attacment, #send-mail, #smtp