如何在 C# 中设置多个 SMTP 电子邮件服务器的主要和备份
how to setup multiple SMTP email servers primary & backup in C#
我正在尝试开发一个电子邮件客户端。将电子邮件发送给给定的收件人
using System.Net;
using System.Net.Mail;
MailMessage msg;
SmtpClient client;
SMTPURL=abc.xyz
SMTPPort=87
client = new SmtpClient(SMTPURL, SMTPPort);
client.Credentials = new NetworkCredential(senderID, senderPWD);
msg = new MailMessage();
msg.To.Add("rx@gmail.com");
msg.Body="hello hi bye";
client.Send(msg);
此代码运行良好,但我有一个备用电子邮件服务器 URL 123.xyz
如果我的 abc.xyz 挂了或者我有错 url 我会得到一个 SMTPException
现在我的问题是如何将我的邮件重新路由到 123.xyz 备份邮件服务器
我的假设是捕获 SMTPException 并将 SMTPURL 更改为 123.xyz 并重新发送,但这是一个好方法还是存在任何其他替代方法来重新路由到辅助邮件服务器 ?
提前致谢
您应该可以使用您的基本 try/catch 块:
public void function sendemail()
{
try{
SendEmailByServer(primaryserverurl);
}
catch(SMTPException se)
{
sendemailbyserver(backupurl);
}
catch(Exception ex)
{
//something else broke
}
}
public void function SendEmailByServer(string server)
{
MailMessage msg;
SmtpClient client;
SMTPURL=server;
SMTPPort=87;
client = new SmtpClient(SMTPURL, SMTPPort);
client.Credentials = new NetworkCredential(senderID, senderPWD);
msg = new MailMessage();
msg.To.Add("rx@gmail.com");
msg.Body="hello hi bye";
client.Send(msg);
}
我正在尝试开发一个电子邮件客户端。将电子邮件发送给给定的收件人
using System.Net;
using System.Net.Mail;
MailMessage msg;
SmtpClient client;
SMTPURL=abc.xyz
SMTPPort=87
client = new SmtpClient(SMTPURL, SMTPPort);
client.Credentials = new NetworkCredential(senderID, senderPWD);
msg = new MailMessage();
msg.To.Add("rx@gmail.com");
msg.Body="hello hi bye";
client.Send(msg);
此代码运行良好,但我有一个备用电子邮件服务器 URL 123.xyz
如果我的 abc.xyz 挂了或者我有错 url 我会得到一个 SMTPException
现在我的问题是如何将我的邮件重新路由到 123.xyz 备份邮件服务器
我的假设是捕获 SMTPException 并将 SMTPURL 更改为 123.xyz 并重新发送,但这是一个好方法还是存在任何其他替代方法来重新路由到辅助邮件服务器 ?
提前致谢
您应该可以使用您的基本 try/catch 块:
public void function sendemail()
{
try{
SendEmailByServer(primaryserverurl);
}
catch(SMTPException se)
{
sendemailbyserver(backupurl);
}
catch(Exception ex)
{
//something else broke
}
}
public void function SendEmailByServer(string server)
{
MailMessage msg;
SmtpClient client;
SMTPURL=server;
SMTPPort=87;
client = new SmtpClient(SMTPURL, SMTPPort);
client.Credentials = new NetworkCredential(senderID, senderPWD);
msg = new MailMessage();
msg.To.Add("rx@gmail.com");
msg.Body="hello hi bye";
client.Send(msg);
}