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

Where is the email attachments ?

If you need email attachments this sample may be helping for you.

Email attachments in the ActivityMimeAttachment entity. Other attachment in the Annotation entity (for default!)

Firstly get email


Entity emailEntity = service.Retrieve("email", new Guid(emailGuidId), new ColumnSet(true));

Here this


QueryExpression qExpression = new QueryExpression();

qExpression.ColumnSet = new ColumnSet(true);
qExpression.EntityName = ActivityMimeAttachment.EntityLogicalName;
qExpression.Criteria.AddFilter(new FilterExpression(LogicalOperator.And));
qExpression.Criteria.AddCondition(new ConditionExpression("ObjectId", ConditionOperator.Equal, emailEntity.Id.ToString()));

var attachments = service.RetrieveMultiple(qExpression);

#attachments, #email, #email-attachments