Click here to Skip to main content
15,890,282 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I want to create a function which sends email to the user from various places
like registeration, change password etc.
It requires to pass different Paramaters according to situation like Email language format or GotoURL in body of email or encrypted password.
can someone tell me should be the best possible function for code maintainability , scalibilty, reusibility.
TIA
Posted
Comments
Sarath kumar.N 13-Aug-15 6:02am    
Sending mail to various places ? Please give more detail. What type of application ? What is the purpose? What is the problem situation
eagertolearnguy 13-Aug-15 6:10am    
I want to create a function which i can use to send email like after registeration
Eg:
"welcome email with activation link"
-For this i need to pass UserLanguage ID ,UserID and url link

or Add Order

"order Added successfull email"
-For this i need to pass UserLanguage ID ,UserID and Order No. to show in email

like wise in future i may have to pass different parameters.
So i want to create a function with multifunctionality
may b using interface or abstract class or constructor etc..

Have an Email helper class that contains a specific method for each type of mail you want to send. This allows you to send just the params you want and also contain this email logic in an email-related class.

C#
public static class EmailHelper
{
    public static void SendRegistrationMail(User user)
    {
        // here I have a User class that the calling code creates.  It has things like the user's nanme, email etc

        // This method is only for registration so we construct the aspects of the mail specific to that
        // we can pass extra params into this function if we want, ot get this data from settings etc

        MailAddress from = new MailAddress("admin@mysite.com", "My Site");
        MailAddress to = new MailAddress(user.Email, user.Name);

        string subject = "Thanks for registering";
        string body = string.Format("Thanks for registering with our site {0}", user.Name);

        // now we've got the data for our registration email we can send it using the generic internal function

        SendEmail(from, to, subject, body);
    }

    public static void SendOrderMail(Basket basket)
    {
        // here I have a Basket class that the calling code creates.  It has things to do with the basket and also a User
        // property

        // This method is only for orders so we construct the aspects of the mail specific to that
        // we can pass extra params into this function if we want, ot get this data from settings etc

        MailAddress from = new MailAddress("admin@mysite.com", "My Site");
        MailAddress to = new MailAddress(basket.User.Email, basket.User.Name);

        string subject = "Thanks for your order";
            
        // construct the body from the Basket object to include the items they have ordered etc
        string body = "Order Summary: ...";

        // now we've got the data for our order email we can send it using the generic internal function

        SendEmail(from, to, subject, body);
    }

    private static void SendEmail (MailAddress from, MailAddress to, string subject, string body)
    {
        // send the email in here
    }
}


Calling code

C#
User user = new User();

user.Email = ".. from form";
user.Name = ".. from form";

EmailHelper.SendRegistrationMail(user);
 
Share this answer
 
ASP.NET MVC has provided you with Controllers, try adding a controller to your application that manages the Emails. Such as,

C#
public class EmailController : Controller 
{
   // Create private and public members for to and from etc. 
   public ActionResult Send(object parameter)
   {
       // Change object to any type, a model or form etc.
   }
   // ... Rest of stuff
}


Now, this can be use from any page. Just submit the form to your /email/ location and controller will be able to send the email to client.

Good thing is that you would be provided with separate Views for this controller and you may want to use a Model (which would hold, details for the email. Such as To, From, Subject, Body etc.) Then you can pass that model to Send action and action may send the email by using the member fields in the Model object. This way, you will be able to set up some parameters the one you are talking about, Email language, GotoUrl etc.

Anyways, you must also consider keeping the passwords safe somewhere, do not expose them to the public.
 
Share this answer
 
Comments
eagertolearnguy 13-Aug-15 6:18am    
I want to create a function which i can use to send email from back end like after registeration
Eg:
"welcome email with activation link"
-For this i need to pass UserLanguage ID ,UserID and url link

or Add Order

"order Added successfull email"
-For this i need to pass UserLanguage ID ,UserID and Order No. to show in email

like wise in future i may have to pass different parameters.
So i want to create a function with multifunctionality
may b using interface or abstract class or constructor etc.
Afzaal Ahmad Zeeshan 13-Aug-15 6:42am    
Indeed, just create this string buffer in the model or the Send function itself. Email controller is just abstraction create to differentiate controllers. Also I find it easy to create a separate controller for every service.

This body of the email can be generated using string.Format() or StringBuilder. Did you understand these concepts? If you did, you would have known that this functionality has great reusability in it. You can add more functions (actions) more features services etc. While you are stuck at just adding the email body content?
eagertolearnguy 13-Aug-15 6:52am    
I'm facing no problem in sending email or body format.I feel i have written bad code and i want to rewrite it with good implementation

I have created a static concrete class which i am calling after save functionality like

email.Send(fromParameter, ToParamter,etc.. );

but then i have to increase parameter with every new email implementation.
and pass null if i dont have to use the parameter and then increase if else condition in the function email.send(){}



Afzaal Ahmad Zeeshan 13-Aug-15 6:55am    
Yes, a class would be an easy implementation.

As far as that parameters problems is concerned. For that sake I would use a separate class, such as EmailMessage. This object can hold the properties that you have right now, or are you going to hold in future. Then in the email.Send you can use those properties from the object and generate the body. Did I make myself clear enough?
eagertolearnguy 13-Aug-15 6:57am    
Welll thanqu for your patience with me.
I think i dont need to use controller because this is a backend process and i dont need to show anything to user about the email.

if you want it to be pretty, functional and available everywhere, this is what I would do:

1. Create a main private base function for sending email.
2. Create a private function for each type of email that will invoke the base function with the right parameters.
3. Create an Enum with email types.
4. Create a public static function that will take the parameters along with Enum parameter (from number 3) which will according to the Enum invoke the right private function, and put that function in a static class that will be outside of any namespace... something like NativeMethods etc...

*Also I would create the base email function to work in a Task, so if I takes long time it won't freeze the main thread.
 
Share this answer
 
Try below code to send mail using gmail.

C#
public string senMail(string emailId, string MailBody)
        {
            try
            {
                MailMessage mail = new MailMessage();
                SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com"); //Gmail SMTP Client

                mail.From = new MailAddress("abc@gmail.com"); //Sender email ID 
                mail.To.Add(emailId);
                mail.Subject = "Email Subject";
                mail.Body = mailBody;

                SmtpServer.Port = 587;
                SmtpServer.Credentials = new System.Net.NetworkCredential("abc@gmail.com", "abc152wte.7"); //Sender email and password (login credential)
                SmtpServer.EnableSsl = true;
                SmtpServer.Send(mail);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            return "";
        }
 
Share this answer
 
Hi,

below is the generic code to implement Email functionality :

public static bool SendMail(string mailTo, string mailFrom, string mailcc, string mailSubject, string filepath, bool isHtml, ListDictionary replacements, string mailBody, List<memorystream> attachmentFiles = null, List<string> fileNamesList = null, List<string> fileContentType = null)
        {

            bool isSend;

            try
            {
                // string mailBody;
                if (!string.IsNullOrEmpty(filepath))
                {
                    using (StreamReader sr = new StreamReader(filepath))
                    {
                        mailBody = sr.ReadToEnd();
                    }
                }

                if (!string.IsNullOrEmpty(mailBody))
                {

                    string mailServer = Convert.ToString(ConfigurationManager.AppSettings["SMTPServer"]);
                    string username = Convert.ToString(ConfigurationManager.AppSettings["SMTP_Username"]);
                    string password = Convert.ToString(ConfigurationManager.AppSettings["SMTP_Password"]);
                    int portAddress = Convert.ToInt32(ConfigurationManager.AppSettings["SMTP_Port"]);

                    bool useDefaultCredentials = Convert.ToBoolean(ConfigurationManager.AppSettings["SMTP_UseDefaultCredentials"]);

                    MailMessage mailmsg = new MailMessage();
                    MailAddress mailFromAdrs = new MailAddress(mailFrom);

                    mailmsg.From = mailFromAdrs;
                    mailmsg.To.Add(mailTo);

                    if (!string.IsNullOrEmpty(mailcc))
                        mailmsg.CC.Add(mailcc);

                    if (replacements != null)
                    {
                        IEnumerator iEnumReplacements = replacements.GetEnumerator();
                        bool hasValues = iEnumReplacements.MoveNext();
                        while (hasValues)
                        {
                            DictionaryEntry lstReplacements = (DictionaryEntry)iEnumReplacements.Current;
                            mailSubject = mailSubject.Replace(lstReplacements.Key.ToString(), lstReplacements.Value.ToString());
                            mailBody = mailBody.Replace(lstReplacements.Key.ToString(), lstReplacements.Value.ToString());

                            hasValues = iEnumReplacements.MoveNext();
                        }
                    }

                    mailmsg.Subject = mailSubject;
                    mailmsg.Body = mailBody;
                    mailmsg.IsBodyHtml = isHtml;

                    if (attachmentFiles != null && attachmentFiles.Count() > 0)
                    {
                        for (int i = 0; i < attachmentFiles.Count(); i++)
                        {                           
                            if (fileNamesList != null && fileContentType != null)
                                mailmsg.Attachments.Add(new Attachment(attachmentFiles[i], fileNamesList[i], fileContentType[i]));
                        }
                    }

                    NetworkCredential smtpUserInfo = new NetworkCredential(username, password);
                    SmtpClient smtpclient = new SmtpClient { Host = mailServer };
                    if (portAddress > 0)
                        smtpclient.Port = portAddress;
                    smtpclient.UseDefaultCredentials = false;


                    if (useDefaultCredentials)
                        smtpclient.UseDefaultCredentials = true;
                    else
                        smtpclient.Credentials = smtpUserInfo;

                    smtpclient.Send(mailmsg);

                    isSend = true;
                }
                else
                    isSend = false;
            }
            catch
            {
                isSend = false;
            }

            return isSend;
        }</string></string></memorystream>
 
Share this answer
 
v2
Comments
Suket shah 17-Aug-15 1:44am    
i don't know why u have given negative ranking but its really helpful code.if you can explain me so i will try to improve.
Thanks.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900