Note that there are some explanatory texts on larger screens.

plurals
  1. POIntercept e-mails before sending (SmtpClient)
    primarykey
    data
    text
    <p>I'm using the following code to send an e-mail:</p> <pre><code>using (var mailMessage = new MailMessage("from@example.com", "to@example.com")) { mailMessage.Subject = "My topic"; mailMessage.IsBodyHtml = true; mailMessage.Body = "My content"; using (var smtpClient = new SmtpClient()) { smtpClient.Send(mailMessage); } } </code></pre> <p>I would like to be able to intercept the e-mail, and change the subject as well as the receiver, when I'm using this code in my test environment. I want to be able to configure something like this in my web.config file:</p> <pre><code>&lt;appSettings&gt; [...] &lt;add key="RedirectAllEmailsTo" value="someone.else@example.com" /&gt; &lt;/appSettings&gt; </code></pre> <p>When the value of "RedirectAllEmailsTo" isnt empty, I would like all the e-mails in my application, to be sent to the specified e-mail, instead of the assigned receiver in my <strong>MailMessage</strong> instance.</p> <p>I would also like to change the topic of the <strong>MailMessage</strong> to indicate who's supposed to receive the e-mail to something like this: "My topic (receiver: to@example.com)".</p> <p>Is it possible to intercept e-mails, and change the receiver as well as the subject, or do I have to write my own class, instead of using SmtpClient directly?</p> <p>This is my code. Hopefully there's a better way to handle it.</p> <pre><code>public static void SendEmail(MailMessage mailMessage) { var redirectAllEmailsTo = ConfigurationManager.AppSettings["RedirectAllEmailsTo"]; if (string.IsNullOrEmpty(redirectAllEmailsTo) == false) { mailMessage.Subject += string.Format(" (to: {0}, cc: {1}, bcc: {2})", string.Join(", ", mailMessage.To.Select(m =&gt; m.Address)), string.Join(", ", mailMessage.CC.Select(m =&gt; m.Address)), string.Join(", ", mailMessage.Bcc.Select(m =&gt; m.Address))); mailMessage.To.Clear(); mailMessage.CC.Clear(); mailMessage.Bcc.Clear(); mailMessage.To.Add(redirectAllEmailsTo); } using (var smtpClient = new SmtpClient()) { smtpClient.Send(mailMessage); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload