IMG-LOGO

How to send an email with dynamic attachment xml generated in ASP.Net C#?

andy - 07 Aug, 2013 7123 Views 0 Comment

This tutorial will show you how you can send an email with dynamic attachment xml generated in ASP.Net C#.

    
//required .net objects
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
using System.IO;
    
//Sample function only that will return an xml in string format
public string CreateXMLLicenseString(){
    return "My sample data";
}
    
//function to send email
//will return empty string if success otherwise will return error message
public string SendMail(string emailFrom, string emailTo, string cc, string subject, string body, string host, int port, string username, string password, bool isHTML, bool enableSSL, Attachment attachment){
    //declare objects
    MailMessage message = new MailMessage();
    SmtpClient smtp = new SmtpClient(host, port);

    //add try exception
    try{
        //Add email address, cc
        message.From = new MailAddress(emailFrom);
        message.To.Add(new MailAddress(emailTo));
        if(cc != string.Empty){
            message.CC.Add(new MailAddress(cc));
        }
            
        //Add subject, body and attachment
        message.Subject = subject;
        message.Body = body;
        if(attachment != null){
            message.Attachments.Add(attachment);
        }
            
        //Email Authentication
        if(username.Trim() != string.Empty && password.Trim() != string.Empty){
            NetworkCredential basicAuthentication = new NetworkCredential(username, password);
            smtp.UseDefaultCredentials = false;
            smtp.Credentials = basicAuthentication;
        }
           
        //enable SSL
        smtp.EnableSsl = enableSSL;
            
        //smtp port
        if (port > 0) { smtp.Port = port; }
            
        //check if html format is needed
        if (isHTML) { message.IsBodyHtml = true; } else { message.IsBodyHtml = false; }
            
        //Send the email
        smtp.Send(message);
    }catch (Exception ex){
        return ex.Message.ToString();
    }
    return "";
}

Comments

There are no comments available.

Write Comment
0 characters entered. Maximum characters allowed are 1000 characters.

Related Articles

How to remove html tags from string in c#?

Sometimes you need to remove HTML tags from string to ensure there are no dangerous or malicious scripts especially when you want to store the string or data text into the database.