Sunday, September 25, 2011

Sending email with embeded image

I have written some articles on sending email from .net application. In this article I will show you a tricky way of sending embeded image to your mail.

The trick to embed image is to create an alternative view and to add a linked resource to the alternative view. Alternative views enable you to create different versions of the email message -- typically one in plain text and the other formatted with HTML. These then substitute for the basic msg.Body property.

To do the actual embedding, you need to do a number of things:
  • Create an HTML-formatted message.
  • Use an <img> tag in the message body.
  • For the src attribute of the <img>, point to a content ID (cid). This points to the portion of the message containing the image stream.
  • Create an alternative view.
  • Create a linkedResource that slurps up the image you want to embed.
  • Assign a content ID to the linked resource -- this should match the cid you used in the <img> tag.
  • Assign the image's file name to the linked resource.

Here is example code sample:

protected void btnSend_Click(object sender, EventArgs e)
    {
        MailMessage mail = BuildMail();
        SendEMail(mail);
    }

private MailMessage BuildMail()
    {
        string from, to, bcc, cc, subject, body;
        from = "uniquesaiful@gmail.com";   //Email Address of Sender
        to = "tips.asp.net@gmail.com,saifulondotnet@gmail.com,uniquesaiful@gmail.com";   //Email Address of Receiver
        bcc = "";
        cc = "";
        subject = "This is a test email. I am just checking whether email client is working properly.";
 
        string imagePath = Server.MapPath("~") + "\\";
        string fileName = imagePath + "Logo.JPG";
 
        StringBuilder sb = new StringBuilder();
        sb.Append("Hi Scott,<br/>");
        sb.Append("This is a test email. We are testing out email client. Please don't mind.<br/>");
        sb.Append("We are sorry for this unexpected mail to your mail box.<br/>");
        sb.Append("<br/>");
        sb.Append("Thanking you<br/>");
        sb.Append("Tips.Asp.Net");
 
        body = sb.ToString();
 
        AlternateView av = AlternateView.CreateAlternateViewFromString(body, nullMediaTypeNames.Text.Html);
        LinkedResource linkedRes = new LinkedResource(fileName);
        linkedRes.ContentId = "image1";
        linkedRes.ContentType.Name = fileName;
        av.LinkedResources.Add(linkedRes);
 
 
        MailMessage mail = new MailMessage();
        mail.From = new MailAddress(from);
        if (to.Contains(","))
        {
            string[] tos = to.Split(',');
            for (int i = 0; i < tos.Length; i++)
            {
                mail.To.Add(new MailAddress(tos[i]));
            }
        }
        else
        {
            mail.To.Add(new MailAddress(to));
        }
 
        if (!string.IsNullOrEmpty(bcc))
        {
            mail.Bcc.Add(new MailAddress(bcc));
        }
        if (!string.IsNullOrEmpty(cc))
        {
            mail.CC.Add(new MailAddress(cc));
        }
 
        mail.Subject = subject;
        mail.Body = body;
        mail.AlternateViews.Add(av);
        mail.IsBodyHtml = true;
 
        return mail;
    }
 
    private void SendEMail(MailMessage mail)
    {
        SmtpClient client = new SmtpClient();
        client.Host = "smtp.gmail.com";
        client.Port = 587;
        client.EnableSsl = true;
        client.Credentials = new System.Net.NetworkCredential("uniquesaiful"ami@janina.com);
        try
        {
            client.Send(mail);
        }
        catch (Exception ex)
        {
            throw ex;
        }
 
    }



Saturday, September 24, 2011

How can I send email easily in asp.net 1.1 version?

Problem: 
 I need to implement email sending functionality on one of my project but the project was developed on .Net framework 1.1 version and clients don't want to upgrade at this moment for some reasons. So is there any component that will allow me to develop that page easily.

Solution:
For those who are still working with ASP.NET 1.1, DotNetOpenMail (http://dotnetopenmail.sourceforge.net/) is a great library. It is a freely available open-source component written in C# that makes it easy to create HTML and plain text email with file attachments without needing the System.Web.Mail library. It allows inline graphics as well as SMTP authentication.

System.Net.Mail being redirected to other addresses

Problem: 
I have a small aspx site setup that uses System.Net.Mail on a few pages to send mail using Godaddy's relay-hosting.secureserver.net.  The site is hosted there as well.   The site will send me an email when someone logs in, visits certain pages, or when a client updates their information.  All of these emails are set to be From my address and To my address and it works fine.  What's happening however is about once a day, I'll get a mailer-daemon message saying that  the mail message  was not deliverable to about 15-20 addresses.  The content of the message is exactly like I would expect from my site, so it's not been changed for spamming.   I don't recognize any address nor are any of these addresses in the database the site uses nor are they anywhere in the directory of the site.

Solution:
 The answer is to use an alternative  for relay-hosting.secureserver.net.
The email server don't support that the email have too much email address.
You can try another email server to test it.

Thursday, September 15, 2011

ASP.NET MVC4 Developer Preview Released

 Microsoft has published ASP.NET MVC4 Developer Preview release. They have added a new page on ASP.NET MVC4 on www.asp.net site. The page link is: http://www.asp.net/mvc/mvc4 . You require Visual Studio 2010 or greater to install ASP.NET MVC4.

You can install it via Web Platform installer:

Some new features introduced in ASP.NET MVC 4 Developer Preview are listed here:
  • Enhancements to Default Project Templates: The new ASP.NET MVC4 project template has been updated to provide modern look and feel to your website.
  • Mobile Project Template: New Mobile Application Project template added to create mobile specific application.
  • Display Modes: This new feature enables you to select views depending on your browser.
  • jQuery Mobile, the View Switcher, and Browser Overriding:
  • Task Support for Asynchronous Controllers 

Saturday, September 10, 2011

How to Encrypt and Decrypt string?

Solution:
Following code examples show the way. It requires two references to include:

using System.Text;
using System.Security.Cryptography;

public static string Encrypt(string toEncrypt, bool useHashing)
        {

            byte[] keyArray;
            byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);

            string key = "MySeCrEtKeY";

            if (useHashing)
            {
                MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
                keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
                hashmd5.Clear();
            }
            else
                keyArray = UTF8Encoding.UTF8.GetBytes(key);

            TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
            tdes.Key = keyArray;
            tdes.Mode = CipherMode.ECB;
            tdes.Padding = PaddingMode.PKCS7;

            ICryptoTransform cTransform = tdes.CreateEncryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            tdes.Clear();
            return Convert.ToBase64String(resultArray, 0, resultArray.Length);
        }




public static string Decrypt(string cipherString, bool useHashing)
        {
            byte[] keyArray;
            byte[] toEncryptArray = Convert.FromBase64String(cipherString);

            string key = " MySeCrEtKeY";

            if (useHashing)
            {
                MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
                keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
                hashmd5.Clear();
            }
            else
                keyArray = UTF8Encoding.UTF8.GetBytes(key);

            TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
            tdes.Key = keyArray;
            tdes.Mode = CipherMode.ECB;
            tdes.Padding = PaddingMode.PKCS7;

            ICryptoTransform cTransform = tdes.CreateDecryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

            tdes.Clear();
            return UTF8Encoding.UTF8.GetString(resultArray);
        }


Hope this will help.

Friday, September 9, 2011

How can I convert my VB.Net code to C# code and Vice Versa?


Solution:
 devloperFusion.com provides a free online tool that makes that conversion tasks very easy for developers. You can convert VB.Net code to C#, Python or Ruby code as well as C# code to VB.Net, Python or Ruby. This tool supports upto .net 3.5 syntax. To use the tool go to:
Convert VB.NET to C#
Convert C# to VB.NET


Thursday, September 8, 2011

How can I install asp.net membership schema in my existing database?

Installing membership related schema to an existing database is very easy task. Asp.net SQL Server Registration Tool(aspnet_regsql.exe) provides a very easy way to achieve the goal. We can run the registration tool from from Visual Studio Command Prompt or we can navigate to aspnet_regsql.exe file location and run the file.

To run from command prompt navigate to:
Start Menu> Microsoft Visual Studio 2010> Visual Studio Tools>Visual Studio Command Prompt(2010)
In the command prompt write aspnet_regsql command and press enter key as the screen shows.

To run from aspnet_regsql.exe  file location navigate to:
%Windows%\Microsoft.NET\Framework\v4.0.30319 and double click on aspnet_regsql.exe to run the tool.

ASP.NET SQL Server Setup Wizard will be appeared as follows:



Press Next button and you will get following screen:


On the next screen you will be prompted to select the database with credentials to which you want to setup membership.


Click Next to confirm your settings and click next again to execute the wizard and finally asp.net membership schema will be created on your database.

If you are interested to know more on asp.net membership you can navigate here:
Examining ASP.NET's Membership, Roles, and Profile

Thanks