Showing posts with label Email. Show all posts
Showing posts with label Email. Show all posts

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.

Saturday, August 20, 2011

How to send attachment with email?


To attach a file with your mail, add it to the mail by MailMessage.Attachments.Add() method.  The simple way to add a file to mail is to specify the file name.
MailMessage mail = new MailMessage();
 mail.Attachments.Add(new Attachment("FileName.txt"));

You can also specify a MIME content type which requires System.IO and System.Net.Mime namespace in addition to System.Net.Mail. The following code sample demonstrates how to use a Stream as a file attachment and how to specify MIME type:
MailMessage mail = new MailMessage();
Stream sr= new FileStream(@"FileName.txt", FileMode.Open, FileAccess.Read);
Mail.Attachments.Add(new Attachment(sr,” FileName.txt”, MediaTypeNames.Application.Octet));

How can I get a delivery failed notification to sender email when sent email fails to deliver?


MailMessage class have a property named “DeliveryNotificationOptions” and an enumeration of type “DeleiveryNotificationOptions”. DeleiveryNotificationOptions enumeration have values: OnSuccess, OnFailure, Delay, None and Never. You can instruct the SMTP server to send a message to the address of email sender specified in MailMessage.From if message delivery fails, delayed or successfully delivered etc. Following code snippet shows how to set for OnFailure:
MailMessage mail = new MailMessage();
mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;

Sending mail to multiple recipient


For sending mail to multiple recipients you can use BCC to send Blind Carbon Copy to each recipient. When you specify recipient in Bcc they will receive message, but the names will not be visible to other recipients.
But instead of using BCC, you should send a separate copy of your message to each recipient that you want to receive blind copy. The problem with BCC is that spam filters frequently block messages that do not have recipient’s email address in the From header. Therefore, if you use BCC, the message will very likely be filtered.
In my previous post I have shown how to send email. Here I would like to rewrite BuildMail() method for sending mail to multiple recipient at a time:
    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.";
 
        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() ;
 
        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))
        {
            if (bcc.Contains(","))
            {
                string[] bccs = bcc.Split(',');
                for (int i = 0; i < bccs.Length; i++)
                {
                    mail.Bcc.Add(new MailAddress(bccs[i]));
                }
            }
            else
            {
                mail.Bcc.Add(new MailAddress(bcc));
            }
        }
        if (!string.IsNullOrEmpty(cc))
        {
            if (cc.Contains(","))
            {
                string[] ccs = cc.Split(',');
                for (int i = 0; i < ccs.Length; i++)
                {
                    mail.CC.Add(new MailAddress(ccs[i]));
                }
            }
            else
            {
                mail.CC.Add(new MailAddress(bcc));
            }
            mail.CC.Add(new MailAddress(cc));
        }
 
        mail.Subject = subject;
        mail.Body = body;
        mail.IsBodyHtml = true;
        mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
 
        return mail;
    }

Tuesday, August 16, 2011

How to send email from Gmail in asp.net?

If you don't have an smtp server for sending email then Gmail can be a cool alternative for you. Sending email from smtp.gmail.com using system.net.mail requires a secured connection. So you have to set SmtpClient's EnableSsl property to true. In this example, we are not writing anything in web.config file. Instead we are writing those configuration information on code behind.

Code for sending email from gmail:


using System;
using System.Net.Mail;
using System.Text;
 
public partial class Mailer : System.Web.UI.Page
{
 
    private MailMessage BuildMail()
    {
        string from, to, bcc, cc, subject, body;
        from = "uniquesaiful@gmail.com";   //Email Address of Sender
        to = "tips.asp.net@gmail.com";   //Email Address of Receiver
        bcc = "";
        cc = "";
        subject = "This is a test email. I am just checking whether email client is working properly.";
 
        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() ;
 
        MailMessage mail = new MailMessage();
        mail.From = new MailAddress(from);
        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.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;
        }
        
    }
    protected void Page_Load(object sender, EventArgs e)
    {
 
    }
    protected void btnSend_Click(object sender, EventArgs e)
    {
        MailMessage mail = BuildMail();
        SendEMail(mail);
    }
}
 
 Following picture is shows the sent email in my inbox: