0

i trying to send test email from my local dev machine, with an image. the image is not being sent as an attachment. May be its a stupid question but is there any way i can send email from my website running on my local machine for test purposes before i host it on www.

public static void SendMail(string emailBody, string to, string from, string subject)
{
    MailMessage mailMessage = new MailMessage("to@to.com", "from@test.com");
    mailMessage.Subject = subject;
    mailMessage.Body = emailBody;
    mailMessage.IsBodyHtml = true;
    //mailMessage.Body += "<br /><br /> <asp:Image ID='Image1' runat='server' ImageUrl='~/images/banner.jpg' />";

    string path = System.Web.HttpContext.Current.Server.MapPath(@"~/images/banner.jpg"); 
    AlternateView av1 = AlternateView.CreateAlternateViewFromString("<html><body><br/><img src=cid:companylogo/><br></body></html>" + emailBody, null, MediaTypeNames.Text.Html);LinkedResource logo = new LinkedResource(path);
    av1.LinkedResources.Add(logo);
    mailMessage.AlternateViews.Add(av1);

    string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
    using (SqlConnection con = new SqlConnection(cs))
    {
        SqlCommand sc = new SqlCommand("SELECT EmailAdd FROM Volunteers where Country like 'United K%' and Race like 'Pak%' ", con);
        con.Open();
        SqlDataReader reader = sc.ExecuteReader();
        if (reader.HasRows)
        {
            while (reader.Read())
            {
                mailMessage.To.Add(reader[0].ToString());
            }
        }
        reader.Close();
    }

    SmtpClient smtpClient = new SmtpClient();
    smtpClient.Send(mailMessage);
}
abatishchev
  • 98,240
  • 88
  • 296
  • 433
GROVER_SYAAN
  • 355
  • 1
  • 5
  • 18
  • 1
    `"is there any way i can send email from my website running on my local machine for test purposes"` - Yes, absolutely. Run a local SMTP listener for testing: http://smtp4dev.codeplex.com – David Feb 07 '14 at 00:21
  • 1
    How do you distinct and don't confuse with variables like `cs` and `sc`? I'd name them more meaningfully. – abatishchev Feb 07 '14 at 00:49

2 Answers2

0

It looks as though you may not be setting the correct CID of the image. This is the method I'm using in one of my applications:

// Construct the MailMessage object to be relayed to the SMTP server
message = new MailMessage("to@to.com", "from@test.com");

string path = System.Web.HttpContext.Current.Server.MapPath(@"~/images/banner.jpg"); 
byte[] image = LoadImageAsByteArray(path);

// create a stream object from the file contents
var stream = new MemoryStream(image);

// create a mailAttachment object
var mailAttachment = new System.Net.Mail.Attachment(stream, "bannerAttachment.jpg")
                     {
                       // set the content id of the attachment so our email src links are valid
                       ContentId = Guid.NewGuid().ToString("N")
                     };

// set the attachment inline so it does not appear in the mail client as an attachment
mailAttachment.ContentDisposition.Inline = true;

// and then add the newly created mailAttachment object to the Attachments collection
message.Attachments.Add(mailAttachment);

And...one thing I found "strange" is your use of AlternateView - it seems a bit redundant. I'd advise creating the body like so:

// Construct the body 
var body = string.Format("<html><body><br/><img src=cid:{0} /><br />{1}</body></html>", mailAttachment.ContentId, emailBody);

// Subject
message.Subject = "Whatever"

// Ensure this is set to true so images are embedded correctly
message.IsBodyHtml = true;

// finally, add the body
message.Body = body;

// Create an smtp client object to initiate a connection with the server
var client = new SmtpClient(smtpServerAddress, smtpServerPort.Value);

// tell the client that we will be sending via the network (as opposed to using a pickup directory)
client.DeliveryMethod = SmtpDeliveryMethod.Network;

// and finally send the message
client.Send(message);

);

NOTE: You'll have to take care of your own authentication etc. as I have not included that. Also, this is an excerpt of my own production code, so please, let me know how you go. I'll be more than happy to modify my answer accordingly.

agAus
  • 675
  • 1
  • 7
  • 11
  • where does this LoadImageAsByteArray function comes from , its not declared not recognized, is there any dll i need to reference to use this. – GROVER_SYAAN Feb 07 '14 at 19:49
  • Sorry, I thought that was self explanatory. I've used the method described here: http://stackoverflow.com/questions/1131116/pdf-to-byte-array-and-vice-versa OR, you could use the method described here: http://stackoverflow.com/questions/7350679/convert-a-bitmap-into-a-byte-array-in-c – agAus Feb 09 '14 at 02:54
  • It'd be nice to know whether this worked for you or not mate? – agAus Feb 11 '14 at 05:37
  • i havent tried it, as without attaching image the mail process is taking too long. since i am sending email to many recipient. i will first address that issue in a separate post before i revisit, but will update the status here – GROVER_SYAAN Feb 11 '14 at 21:23
0

here is your solution.

 string ss = "<div style='background:#e0e1e3;width:800px; margin:20px auto;border:1px solid #d8d9db;'>";
                ss = ss + "<div style='background:#ffffff; padding:10px;'>";
                ss = ss + "<img src='http://example.com/images/myimage.jpg'  /></div>";



    MailMessage MailMsg = new MailMessage();
                MailMsg.To.Add("test@test.com");
                MailMsg.From = new MailAddress("Test.co.in");
                MailMsg.Subject = "Your subject";
                MailMsg.BodyEncoding = System.Text.Encoding.UTF8;
                MailMsg.IsBodyHtml = true;
                MailMsg.Priority = MailPriority.High;
                MailMsg.Body = ss;
    SmtpClient tempsmtp = new SmtpClient();
                tempsmtp.Host = "smtp.gmail.com";
                tempsmtp.Port = 587;
                tempsmtp.EnableSsl = true;
                tempsmtp.Credentials = new System.Net.NetworkCredential("test@test.com", "welcome");
tempsmtp.DeliveryMethod = SmtpDeliveryMethod.Network;
            tempsmtp.Send(MailMsg);
angfreak
  • 993
  • 2
  • 11
  • 27
  • it seems the image that you are using is placed on web, my image is on my local solution folder, i want to attach it with the email. i am testing that functionality before i deploy solution to web server. – GROVER_SYAAN Feb 07 '14 at 19:48