?
Solved

Good example of email helper class to send email

Posted on 2008-10-23
4
Medium Priority
?
3,501 Views
Last Modified: 2013-12-17
I need to send email using c# .net 3.5.  Now I want to encapsulate all of this in a class - I greately need example please

Thanks you
0
Comment
Question by:mugsey
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
4 Comments
 
LVL 16

Expert Comment

by:Gyanendra Singh
ID: 22784389
Here is a simple snippet of how to send an email message from sender@foo.bar.com to multiple email recipients (note that the To a CC properties are collections and so can handle multiple address targets):

 

MailMessage message = new MailMessage();

message.From = new MailAddress("sender@foo.bar.com");

 

message.To.Add(new MailAddress("recipient1@foo.bar.com"));

message.To.Add(new MailAddress("recipient2@foo.bar.com"));

message.To.Add(new MailAddress("recipient3@foo.bar.com"));

 

message.CC.Add(new MailAddress("carboncopy@foo.bar.com"));

message.Subject = "This is my subject";

message.Body = "This is the content";

 

SmtpClient client = new SmtpClient();

client.Send(message);

 

System.Net.Mail reads SMTP configuration data out of the standard .NET configuration system (so for ASP.NET applications youd configure this in your applications web.config file).  Here is an example of how to configure it:

 

  <system.net>

    <mailSettings>

      <smtp from="test@foo.com">

        <network host="smtpserver1" port="25" userName="username" password="secret" defaultCredentials="true" />

      </smtp>

    </mailSettings>

  </system.net>

 

Hope this helps,

0
 

Author Comment

by:mugsey
ID: 22784495
Thank you


What is the best way to encapsulate this in class - I want to have a class method "sendEmail"  and pass in paramters
0
 
LVL 10

Accepted Solution

by:
jinn_hnnl earned 1000 total points
ID: 22784524
Look at this,

This is the one I use (I have a more complicated one, but this will do), with an example, you can plug it in your project and use it right away, now I put static method to make it easier to access, modify the way you want it.

using System;
using System.Data;
using System.Configuration;
using System.Web.Mail;
using System.Text;
 
namespace JinnProject
{
    public class Emailing
    {
        private const string BREAK_LINE = "<br />";
        public static int ComposeAndSendEmail(string to, string from, string subject, string message)
        {
            MailMessage objMail = new MailMessage();
            objMail.To = to;
            objMail.From = from;
            objMail.Subject = subject;
            objMail.Body = message;
            objMail.BodyFormat = MailFormat.Html;
 
            try
            {
                SmtpMail.Send(objMail);   
                return 1;
            }
            catch (Exception ex)
            {
                return -1;
            }            
        }
 
	
	//call this from anywhere for example : 
	// int sentmailstatus = SendResetPassEmail("jinn", "abc", "jinn@jinn.com")
        public static int SendResetPassEmail(string username, string newPass, string useremail)
        {
            StringBuilder strBodyText = new StringBuilder();
            strBodyText.Append("Dear " + user.Lastname + ", <br />");
            strBodyText.Append(BREAK_LINE);
            strBodyText.Append("Your login information to our server has been changed. This is your login details: <br />");
            strBodyText.Append(BREAK_LINE);
            //strBodyText.Append("Username: " + user.Username + " <br />");
            strBodyText.Append("Username: " + username + " <br />");
            strBodyText.Append("Password: " + newPass +  "<br />");
            strBodyText.Append(BREAK_LINE);
            strBodyText.Append("Please be aware that this login details can only be used once, you have to immediately change your password after your first login using this details.");
            strBodyText.Append(BREAK_LINE);
            strBodyText.Append(BREAK_LINE);
            strBodyText.Append("Best regards, <br />");
            strBodyText.Append("Administrator.");
            return ComposeAndSendEmail(useremail, "noreply@jinnhost.nl", "Login information", strBodyText.ToString());
        }
    }
}

Open in new window

0
 
LVL 16

Assisted Solution

by:Gyanendra Singh
Gyanendra Singh earned 1000 total points
ID: 22784596
please find sample class
Calling the function from code
 
MailHelper.SendMailMessage("fromAddress@yourdomain.com", "toAddress@yourdomain.com", "bccAddress@yourdomain.com", "ccAddress@yourdomain.com", "Sample Subject", "Sample body of text for mail message")
 
MailHelper.cs
 
using System.Net.Mail;
 
public class MailHelper
{
   /// <summary>
   /// Sends an mail message
   /// </summary>
   /// <param name="from">Sender address</param>
   /// <param name="to">Recepient address</param>
   /// <param name="bcc">Bcc recepient</param>
   /// <param name="cc">Cc recepient</param>
   /// <param name="subject">Subject of mail message</param>
   /// <param name="body">Body of mail message</param>
   public static void SendMailMessage(string from, string to, string bcc, string cc, string subject, string body)
   {
      // Instantiate a new instance of MailMessage
      MailMessage mMailMessage = new MailMessage();
 
      // Set the sender address of the mail message
      mMailMessage.From = new MailAddress(from);
      // Set the recepient address of the mail message
      mMailMessage.To.Add(new MailAddress(to)); 
      // Check if the bcc value is null or an empty string
      if ((bcc != null) && (bcc != string.Empty))
      {
         // Set the Bcc address of the mail message
         mMailMessage.Bcc.Add(new MailAddress(bcc));
      }
 
      // Check if the cc value is null or an empty value
      if ((cc != null) && (cc != string.Empty))
      {
         // Set the CC address of the mail message
         mMailMessage.CC.Add(new MailAddress(cc));
      }       // Set the subject of the mail message
      mMailMessage.Subject = subject;
      // Set the body of the mail message
      mMailMessage.Body = body; 
      // Set the format of the mail message body as HTML
      mMailMessage.IsBodyHtml = true;
      // Set the priority of the mail message to normal
      mMailMessage.Priority = MailPriority.Normal;
 
      // Instantiate a new instance of SmtpClient
      SmtpClient mSmtpClient = new SmtpClient();
      // Send the mail message
      mSmtpClient.Send(mMailMessage);
   }
}

Open in new window

0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

IntroductionWhile developing web applications, a single page might contain many regions and each region might contain many number of controls with the capability to perform  postback. Many times you might need to perform some action on an ASP.NET po…
Introduction This article shows how to use the open source plupload control to upload multiple images. The images are resized on the client side before uploading and the upload is done in chunks. Background I had to provide a way for user…
This is my first video review of Microsoft Bookings, I will be doing a part two with a bit more information, but wanted to get this out to you folks.
Do you want to know how to make a graph with Microsoft Access? First, create a query with the data for the chart. Then make a blank form and add a chart control. This video also shows how to change what data is displayed on the graph as well as form…
Suggested Courses

777 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question