Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
327 views
in Technique[技术] by (71.8m points)

c# - Capture SMTP errors in .NET

Normally, I'd send emails like that:

int statusCode = 0;
string error = null;

try
{
    smtp.Send(mailMessage);
    statusCode = 250;
}
catch (SmtpFailedRecipientException e)
{
    Log(String.Format("[Exception] {0}
Smtp: {1}{2}:{3}
Status Code: {4}
Faild Recipient: {5}", e.Message, smtp.Key, smtp.Value.Host, smtp.Value.Port, e.StatusCode, e.FailedRecipient));

    statusCode = (int)e.StatusCode;
    error = e.Message;
}
catch (SmtpException e)
{
    Log(String.Format("[Exception] {0}
Smtp: {1} - {2}:{3}
Status Code: {4}", e.Message, smtp.Key, smtp.Value.Host, smtp.Value.Port, e.StatusCode));

    statusCode = (int)e.StatusCode;
    error = e.Message;
}
catch (Exception e)
{
    Log(String.Format("[Exception] {0}.
Source: {1}
Stack Trace: {2}", e.Message, e.Source, e.StackTrace));

    statusCode = -1;
    error = "General Failure";
}

But this method doesn't allow me to catch some of the more "advanced" SMTP errors such as No Domain, No such Email, etc.

How can I capture that kind of SMTP errors? Is that even possible?

For example, when I'm trying to send in Gmail to an address such as [email protected], Gmail sends me after a while an Email that [email protected] doesn't exist.

Thank you.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

SMTP is a "store and forward" protocol, meaning that the server can accept a message for forwarding, but not know at the time that the message can't be delivered. So, for example, when you tell your ISP's SMTP server to deliver a message to "[email protected]", the server's response is, "Okay, I'll forward it." At some later time, the ISP's SMTP server will contact the SMTP server for "example.com", and try to deliver the message. Only then does it know that the mail is undeliverable.

So as far as the communication between your client and the SMTP server is concerned, the message was delivered successfully--the server agreed to forward it. Therefore, no exception.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...