【问题标题】:How C# SMTP worksC# SMTP 的工作原理
【发布时间】:2020-12-02 04:53:48
【问题描述】:

我正在分析一个具有邮件功能的 C# 项目。由于一些限制,我无法运行该项目。我在分析代码时遇到了一些问题

MailAddress toMailAddress = new MailAddress(strToMail);
MailAddress fromMailAddress = new fromMailAddress(strFromMail);
SmtpClient smtpClient = new SmtpClient(smtpServer);
String strBody = strMessage;
MailMessage msg = New MailMessage();
msg.From = fromMailAddress

msg.To.Add(toMailAddress);
msg.Subject = strSubject;
smtpClient.Send(msg);
  1. 这里的发件人地址来自数据库,但在数据库中没有存储相应电子邮件的凭据,也没有通过代码传递。这是否意味着我可以在没有凭据的情况下从任何帐户发送电子邮件?
  2. 发送邮件需要outlook吗?如果是这样,outlook 被配置到不同的帐户而不是代码中的 from 地址,它会抛出任何错误吗?

【问题讨论】:

  • 一些设置可以在web.config中进行配置。 Related question
  • 注意:可以将 SMTP 服务器配置为允许中继(非认证电子邮件),但很可能设置在 web.config 文件中
  • @Cleptus 这是否意味着如果我的 Outlook 帐户配置为 admin@outlook.com 并且发件人地址是 user@outlook.com,它还能工作吗?如果没有相应用户的用户名和密码,我可以从任何电子邮件 ID 发送邮件吗?
  • 当且仅当 SMTP 服务器配置为允许它。不是常见的情况,但如果它允许中继,您可以使用一些凭据进行身份验证并从不同的地址发送
  • Outlook 不是发送电子邮件所必需的。像 GMAIL 这样的邮件服务器接受网络库生成的 SMTP 对象。 GMAIL 需要凭据。默认凭据来自控制面板用户邮件设置(如 POP 帐户)。

标签: c# asp.net .net smtp


【解决方案1】:
  1. 取决于您的 SMTP 服务器的配置方式。在您发布的代码中,它似乎通过默认端口SMTP(可能在25465587)发送电子邮件而没有凭据。也可以在配置文件(web.config、app.config)中进行配置。

  2. 不,您的应用程序在 .net 下运行,Outlook 不会影响它。

【讨论】:

  • 这是否意味着如果我的 Outlook 帐户配置为 admin@outlook.com 并且发件人地址为 user@outlook.com,它仍然可以使用吗?谁将是邮件的发件人?
  • @Jay 检查 web.config 文件并查找 mailSettings 部分
【解决方案2】:
  1. 这取决于 SMTP 配置,可能是因为您尚未配置,您会遇到错误。您面临的确切错误是什么?这是我在代码中用于发送邮件的sn-p,连接和凭据可以由以下sn-p给出,希望对您有帮助!

  2. 据我所知,Outlook 电子邮件不应影响或导致任何错误。

SqlConnection sqlConnection = new SqlConnection();  
    
sqlConnection.ConnectionString = "server = YOURSERVERNAME; database = YOURDBNAME; User ID = sa; Password = YOURPASSWORD"; //Connection Details  
    
//select fields to mail required details  
    SqlCommand sqlCommand = new SqlCommand("select Name,DOB,Email,Mob from Student", sqlConnection); //select query command  
    SqlDataAdapter sqlDataAdapter = new System.Data.SqlClient.SqlDataAdapter();  
    sqlDataAdapter.SelectCommand = sqlCommand;

try
         {
                MailMessage mail = new MailMessage();
                SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");    //This is for creating a gmail client

                mail.From = new MailAddress("your_email_address@gmail.com");
                mail.To.Add("to_address");
                mail.Subject = "Test Mail";
                mail.Body = "Test SMTP mail from GMAIL";

                SmtpServer.Port = 587;
                SmtpServer.Credentials = new System.Net.NetworkCredential("username", "password");
                SmtpServer.EnableSsl = true;

                SmtpServer.Send(mail);
                MessageBox.Show("mail Send");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-17
    • 2014-07-14
    • 2011-04-18
    • 2012-09-02
    • 1970-01-01
    • 1970-01-01
    • 2011-08-03
    • 1970-01-01
    相关资源
    最近更新 更多