2016-11-29 59 views
0

我已經有郵件服務,但我需要使用與地址不同的地址,因爲此服務被許多服務使用。 現在,我有這樣的代碼,它工作正常:使用與地址不同的地址發送郵件

public static bool SendMail(Mail mail) 
{ 
    var smtp = new SmtpClient(); 
    var credential = (NetworkCredential) smtp.Credentials; 
    var mailMessage = new MailMessage 
    { 
     From = new MailAddress(credential.UserName, mail.DisplayName), 
     Subject = mail.Subject, 
     Body = mail.Body, 
     IsBodyHtml = true 
    }; 
    mailMessage.To.Add(new MailAddress(mail.To)); 
    if (!string.IsNullOrEmpty(mail.TemplatePath)) 
     mailMessage = embedImages(mailMessage, mail); 
    smtp.Send(mailMessage); 
    return true; 
} 

> And the web.config: 

<mailSettings> 
    <smtp from="[email protected]"> 
    <network host="smtp.gmail.com" enableSsl="true" port="587" userName="[email protected]" password="123456" /> 
    </smtp> 
</mailSettings> 

> The Mail parameter, is an object: 

public class Mail 
{ 
    public string Subject { get; set; } 
    public string Body { get; set; } 
    public string To { get; set; } 
    public string TemplatePath { get; set; } 
    public string DisplayName { get; set; } 
    public string From { get; set; } 
} 

所以,在默認情況下,它應該使用mailSettings,但是,如果物業mail.From = null,則應該可以通過郵寄!

感謝

+1

然後將地址更改爲類似於NoReply @無論您在代碼中的哪個地方從'mailSettings'中讀取? – MethodMan

回答

0

你試圖從多個從地址發送郵件或你想能夠使用同樣的方法,用不同的地址?

如果您希望能夠在不同時間點將地址與不同的地址重複使用,您可以將方法中的憑據作爲參數傳入。然後,您將能夠根據參數提供的憑據設置smtp。

我沒有看到你正在閱讀你設置的mailSettings的任何地方。所以我不明白你是如何配置你的smtp。

0

以下是我使用SmtpClient發送警報電子郵件的方式。我正在使用ConfigurationManager.AppSettings,但同樣的想法適用於您使用的任何類型的配置文件:嘗試獲取「from」電子郵件,如果它爲null,則使用默認值。

string subject = "Email subject here." 
    string msg = "Email body here."   

    string fromEmail = ConfigurationManager.AppSettings["fromEmail"]; 

    if (fromEmail == null) 
     fromEmail = "[email protected]" 

    string emailServer = ConfigurationManager.AppSettings["emailServer"]; 
    int emailServerPort = int.Parse(ConfigurationManager.AppSettings["emailServerPort"]); 
    string toEmail; //email recipients   

    SmtpClient client = new SmtpClient(emailServer, emailServerPort); 
    MailMessage mail = new MailMessage(fromEmail, toEmail, subject, msg); 
    client.Send(mail); 
相關問題