2011-02-12 8 views
4

나는 전자 메일을 보내는 코드를 정리하려고 내 응용 프로그램을 살펴 보려고합니다. 나 자신의 emailer wrapper 클래스를 만들기 시작했는데, 어딘가에 표준 emailer 클래스가 있어야한다는 것을 알았다. 나는 약간의 검색을했지만 아무것도 찾을 수 없었다.표준 전자 메일 클래스?

또한 여기에 같은 코드 기반이 있습니까?

수정 : 죄송합니다.

내 코드에서 내가 이메일을 보내해야하는 시간이 갖고 싶어하지 않습니다

SendEmail(string to, string from, string body) 
SendEmail(string to, string from, string body, bool isHtml) 
: 내가 좋아하는 기능이 포함되어 이메일 전송 시스템이라는 클래스를 생성
System.Web.Mail.MailMessage message=new System.Web.Mail.MailMessage(); 
message.From="from e-mail"; 
message.To="to e-mail"; 
message.Subject="Message Subject"; 
message.Body="Message Body"; 
System.Web.Mail.SmtpMail.SmtpServer="SMTP Server Address"; 
System.Web.Mail.SmtpMail.Send(message); 

그래서 난 그냥 이메일 보내 내 코드에이 한 줄을 넣을 수 있습니다 :

Emailer.SendEmail("[email protected]", "[email protected]", "My e-mail", false); 

내 말을 너무 아니다 복잡한,하지만 거기에 표준, 수용 솔루션을 생각했습니다.

+1

분명히 말하십시오. "표준 전자 메일 클래스"란 무엇입니까? 양식 필드를 이메일로 바꿔주는 뭔가가 있습니까? – anon

+0

@anon, 동의 함. 나는 OP가 http://msdn.microsoft.com/en-us/library/system.net.mail.aspx에 관해 묻는 것이 아니라고 가정한다. –

+0

@Kirk Woll 사실, 나는 그 사람이라는 인상을받습니다. – GWLlosa

답변

7

이와 비슷한?

using System; 
using System.Net; 
using System.Net.Mail; 
using System.Net.Mime; 
using MailMessage=System.Net.Mail.MailMessage; 

class CTEmailSender 
{ 
    string MailSmtpHost { get; set; } 
    int MailSmtpPort { get; set; } 
    string MailSmtpUsername { get; set; } 
    string MailSmtpPassword { get; set; } 
    string MailFrom { get; set; } 

    public bool SendEmail(string to, string subject, string body) 
    { 
     MailMessage mail = new MailMessage(MailFrom, to, subject, body); 
     var alternameView = AlternateView.CreateAlternateViewFromString(body, new ContentType("text/html")); 
     mail.AlternateViews.Add(alternameView); 

     var smtpClient = new SmtpClient(MailSmtpHost, MailSmtpPort); 
     smtpClient.Credentials = new NetworkCredential(MailSmtpUsername, MailSmtpPassword); 
     try 
     { 
      smtpClient.Send(mail); 
     } 
     catch (Exception e) 
     { 
      //Log error here 
      return false; 
     } 

     return true; 
    } 
} 
+0

예, 감사합니다. 이 코드베이스가있는 코드베이스가 있습니까? 아니면 이와 같은 코드 서비스가있는 코드 기반을 알고 있습니까? – Steven

+0

@Steven : 방금 프로젝트 코드에서 수업을 들었습니다. 70-536 훈련 도서에는 전자 메일 보내기에 대한 좋은 장이 있습니다. – LukLed

+0

초보자 용 질문처럼 들릴 수 있습니다. "MailMessage = System.Net.Mail.MailMessage 사용"문은 무엇입니까? 평균? System.Net.Mail을 이미 가져 왔으므로 코드 없이도 코드가 작동합니다. –

1

어쩌면 당신은 SmtpClient을 찾고 있을까요?

0

this old Stack Overflow Answer으로 만든 제네릭 클래스를 사용합니다.
시도해보십시오.


public bool SendEmail(MailAddress toAddress, string subject, string body) 
{ 
    MailAddress fromAddress = new MailAddress("pull from db or web.config", "pull from db or web.config"); 
    string fromPassword = "pull from db or config and decrypt"; 
    string smtpHost = "pull from db or web.config"; 
    int smtpPort = 587;//gmail port 

    try 
    { 
     var smtp = new SmtpClient 
     { 
      Host = smtpHost, 
      Port = smtpPort, 
      EnableSsl = true, 
      DeliveryMethod = SmtpDeliveryMethod.Network, 
      UseDefaultCredentials = false, 
      Credentials = new NetworkCredential(fromAddress.Address, fromPassword) 
     }; 
     using (var message = new MailMessage(fromAddress, toAddress) 
     { 
      Subject = subject, 
      Body = body, 
      IsBodyHtml = true 
     }) 
     { 
      smtp.Send(message); 
     } 
     return true; 
    } 
    catch (Exception err) 
    { 
     Elmah.ErrorSignal.FromCurrentContext().Raise(err); 
     return false; 
    } 

} 
0

이 내 프로젝트 중 하나에서 미리보기입니다. 다른 구현물보다 조금 더 많은 기능이 추가되었습니다. 이 기능을 사용

당신이 이메일을 만들 수 있습니다 : 런타임에 실제 값으로 텍스트 및 HTML보기를 모두 포함

  • 이메일을 교체 할 수 있습니다

    • 토큰

      public MailMessage createMailMessage(string toAddress, string fromAddress, string subject, string template) 
      { 
      // Validate arguments here... 
      
      // If your template contains any of the following {tokens} 
      // they will be replaced with the values you set here. 
      var replacementDictionary = new ListDictionary 
           { 
            // Replace with your own list of values 
            { "{first}", "Pull from db or config" }, 
            { "{last}", "Pull from db or config" } 
           }; 
      
      // Create a text view and HTML view (both will be in the same email) 
      // This snippet assumes you are using ASP.NET (works w/MVC) 
      // if not, replace HostingEnvironment.MapPath with your own path. 
      var mailDefinition = new MailDefinition { BodyFileName = HostingEnvironment.MapPath(template + ".txt"), IsBodyHtml = false }; 
      var htmlMailDefinition = new MailDefinition { BodyFileName = HostingEnvironment.MapPath(template + ".htm"), IsBodyHtml = true }; 
      
      MailMessage htmlMessage = htmlMailDefinition.CreateMailMessage(email, replacementDictionary, new Control()); 
      MailMessage textMessage = mailDefinition.CreateMailMessage(email, replacementDictionary, new Control()); 
      
      AlternateView plainView = AlternateView.CreateAlternateViewFromString(textMessage.Body, null, "text/plain"); 
      AlternateView htmlView = AlternateView.CreateAlternateViewFromString(htmlMessage.Body, null, "text/html"); 
      
      var message = new MailMessage { From = new MailAddress(from) }; 
      
      message.To.Add(new MailAddress(toAddress)); 
      message.Subject = subject; 
      
      message.AlternateViews.Add(plainView); 
      message.AlternateViews.Add(htmlView); 
      
      return message; 
      } 
      

    NetMail 용 Web.config를 설정했다고 가정하면 다음과 같은 도우미 메서드에서이 메서드를 호출 할 수 있습니다.

    public bool SendEmail(MailMessage email) 
    { 
        var client = new SmtpClient(); 
    
        try 
        { 
         client.Send(message); 
        } 
        catch (Exception e) 
        { 
         return false; 
        } 
    
        return true; 
    } 
    
    SendMail(createMailMessage("[email protected]", "[email protected]", "Subject", "~/Path/Template")); 
    
  • 관련 문제