Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Mailer Class

Tags:

c#

I have a mailer for Google as shown below, how can i adapt this for other mail systems? Is there a better way of doing this? also how can i change the name of where the mail is from(the sender). All help would be much appreciated, and thank you in advance

 MailMessage message = new MailMessage();
        message.From = new MailAddress(MailAddresds);
        message.Subject = messagesubject;
        message.Body = messagebody;


        message.To.Add(messageto);
        SmtpClient client = new SmtpClient();

        client.Credentials = new NetworkCredential(userName, password);
        client.Host = "smtp.gmail.com";
        client.Port = 587;
        client.EnableSsl = true;
        client.Send(message);
like image 657
Jacob O'Brien Avatar asked Jun 18 '26 19:06

Jacob O'Brien


2 Answers

Just example:

public class MailMessage
{
   public string From{get;set;}
   public string To{get;set;}
   public string Body{get;set;}
   public string Subject{get;set;}
   ....
   //other common properties you may need
}


//interface 
public interface IMailService
{
    Send(MailMessage m);
}

concrete implementations:

public class GoogleMail : IMailService
{
    public Send(Message msg)
    { 
       //google mail specific code
    }
}


public class YahooMail : IMailService
{
    public Send(Message msg)
    { 
       //yahoo mail specific code
    }
}

.... Hotmail,...

somewhere in the code create a collection of supported mail services

var mailservices = new List<IMailService>();
mailservices.Add(new GoogleMail ());
mailservice.Add(new YahooMail ());

after, during the program run, pick the appropriate service to proceed user request.

like image 197
Tigran Avatar answered Jun 21 '26 09:06

Tigran


simple example:

using System.Web.Mail;

MailMessage objMessage = new MailMessage();
objMessage.From = "from";
objMessage.To = "to";
objMessage.Subject = "subject";
objMessage.BodyFormat = MailFormat.Text;
objMessage.Body = "body";
SmtpMail.SmtpServer = "SmtpServer";
SmtpMail.Send(objMessage);
like image 27
Diego Avatar answered Jun 21 '26 09:06

Diego