【问题标题】:How to send email in ASP.NET C#如何在 ASP.NET C# 中发送电子邮件
【发布时间】:2013-08-22 00:19:32
【问题描述】:

我对@9​​87654321@ C# 领域非常陌生。我打算通过 ASP.NET C# 发送邮件,这是来自我的ISPSMTP 地址:

smtp-proxy.tm.net.my

以下是我尝试做的,但失败了。

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="SendMail" %>
<html>
<head id="Head1" runat="server"><title>Email Test Page</title></head>
<body>
    <form id="form1" runat="server">
        Message to: <asp:TextBox ID="txtTo" runat="server" /><br>
        Message from: <asp:TextBox ID="txtFrom" runat="server" /><br>
        Subject: <asp:TextBox ID="txtSubject" runat="server" /><br>
        Message Body:<br>
        <asp:TextBox ID="txtBody" runat="server" Height="171px" TextMode="MultiLine"  Width="270px" /><br>
        <asp:Button ID="Btn_SendMail" runat="server" onclick="Btn_SendMail_Click" Text="Send Email" /><br>
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
    </form>
</body>
</html>

下面是我的code-behind

using System;
using System.Web.UI.WebControls;
using System.Net.Mail;
public partial class SendMail : System.Web.UI.Page
{
    protected void Btn_SendMail_Click(object sender, EventArgs e)
    {
        MailMessage mailObj = new MailMessage(
            txtFrom.Text, txtTo.Text, txtSubject.Text, txtBody.Text);
        SmtpClient SMTPServer = new SmtpClient("127.0.0.1");
        try
        {
            SMTPServer.Send(mailObj);
        }
        catch (Exception ex)
        {
            Label1.Text = ex.ToString();
        }
    }
}

PS:很抱歉,我无法理解接收方/发送方 SMTP 概念,因此我试图从这里理解整个概念。

【问题讨论】:

  • 当你点击按钮时,它会到达后面的代码吗?
  • 您是否在 localhost 的 IIS 中设置了 smtp?失败是什么?您有 ISP 的邮件帐户吗?

标签: c# asp.net email smtp


【解决方案1】:

只需通过下面的代码。

SmtpClient smtpClient = new SmtpClient("mail.MyWebsiteDomainName.com", 25);

smtpClient.Credentials = new System.Net.NetworkCredential("info@MyWebsiteDomainName.com", "myIDPassword");
// smtpClient.UseDefaultCredentials = true; // uncomment if you don't want to use the network credentials
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.EnableSsl = true;
MailMessage mail = new MailMessage();

//Setting From , To and CC
mail.From = new MailAddress("info@MyWebsiteDomainName", "MyWeb Site");
mail.To.Add(new MailAddress("info@MyWebsiteDomainName"));
mail.CC.Add(new MailAddress("MyEmailID@gmail.com"));

smtpClient.Send(mail);

【讨论】:

  • Thamotharan's 是正确的。发送纯文本或 HTML 正文。对于快速而肮脏的普通电子邮件。这是在邮件正文中嵌入 HTML 标记的一个很好的示例。 Inline HTML code。 StringBuilder 对于创建更大的消息非常有用。还有
  • 我发现这很有帮助。根据文档,虽然将 UseDefaultCredentials 设置为 true 意味着将不会发送给定的凭据。这是要弄清楚的棘手部分。
  • 请注意,MailMessageSmtpClient 都实现了 IDisposable 并且应该在 using 语句中使用(或以其他方式处理)
  • 可能需要配置一个gmail账号,如下。 “不太安全的应用程序”的值应设置为“启用”。在客户端使用域“smtp.gmail.com”和端口 587。
【解决方案2】:

尝试改用此代码。注意:在“发件人地址”中提供正确的电子邮件 ID 和密码。

protected void btn_send_Click(object sender, EventArgs e)
{

    System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
    mail.To.Add("to gmail address");
    mail.From = new MailAddress("from gmail address", "Email head", System.Text.Encoding.UTF8);
    mail.Subject = "This mail is send from asp.net application";
    mail.SubjectEncoding = System.Text.Encoding.UTF8;
    mail.Body = "This is Email Body Text";
    mail.BodyEncoding = System.Text.Encoding.UTF8;
    mail.IsBodyHtml = true;
    mail.Priority = MailPriority.High;
    SmtpClient client = new SmtpClient();
    client.Credentials = new System.Net.NetworkCredential("from gmail address", "your gmail account password");
    client.Port = 587;
    client.Host = "smtp.gmail.com";
    client.EnableSsl = true;
    try
    {
        client.Send(mail);
        Page.RegisterStartupScript("UserMsg", "<script>alert('Successfully Send...');if(alert){ window.location='SendMail.aspx';}</script>");
    }
    catch (Exception ex)
    {
        Exception ex2 = ex;
        string errorMessage = string.Empty;
        while (ex2 != null)
        {
            errorMessage += ex2.ToString();
            ex2 = ex2.InnerException;
        }
        Page.RegisterStartupScript("UserMsg", "<script>alert('Sending Failed...');if(alert){ window.location='SendMail.aspx';}</script>");
    }
}

【讨论】:

  • 所以我在我的 ASP.net 页面中设置了一个带有下拉列表/文本框的表单。它会以同样的方式工作吗?谢谢。
  • 这段代码在本地服务器机器人上运行,而不是来自托管老爹服务器。为什么?
【解决方案3】:

你可以像这样使用 hotmail 试试这个:-

MailMessage o = new MailMessage("From", "To","Subject", "Body");
NetworkCredential netCred= new NetworkCredential("Sender Email","Sender Password");
SmtpClient smtpobj= new SmtpClient("smtp.live.com", 587); 
smtpobj.EnableSsl = true;
smtpobj.Credentials = netCred;
smtpobj.Send(o);

【讨论】:

    【解决方案4】:

    尝试以下方法:

    try
    {
        var fromEmailAddress =  ConfigurationManager.AppSettings["FromEmailAddress"].ToString();
        var fromEmailDisplayName = ConfigurationManager.AppSettings["FromEmailDisplayName"].ToString();
        var fromEmailPassword = ConfigurationManager.AppSettings["FromEmailPassword"].ToString();
        var smtpHost = ConfigurationManager.AppSettings["SMTPHost"].ToString();
        var smtpPort = ConfigurationManager.AppSettings["SMTPPort"].ToString();
    
        string body = "Your registration has been done successfully. Thank you.";
        MailMessage message = new MailMessage(new MailAddress(fromEmailAddress, fromEmailDisplayName), new MailAddress(ud.LoginId, ud.FullName));
        message.Subject = "Thank You For Your Registration";
        message.IsBodyHtml = true;
        message.Body = body;
    
        var client = new SmtpClient();
        client.Credentials = new NetworkCredential(fromEmailAddress, fromEmailPassword);
        client.Host = smtpHost;
        client.EnableSsl = true;
        client.Port = !string.IsNullOrEmpty(smtpPort) ? Convert.ToInt32(smtpPort) : 0;
        client.Send(message);
    }
    catch (Exception ex)
    {
        throw (new Exception("Mail send failed to loginId " + ud.LoginId + ", though registration done."));
    }
    

    然后在你的 web.config 中添加以下内容

    <!--Email Config-->
    <add key="FromEmailAddress" value="sender emailaddress"/>
    <add key="FromEmailDisplayName" value="Display Name"/>
    <add key="FromEmailPassword" value="sender Password"/>
    <add key="SMTPHost" value="smtp-proxy.tm.net.my"/>
    <add key="SMTPPort" value="smptp Port"/>
    

    【讨论】:

      【解决方案5】:

      你可以试试 MailKit MailKit 是一个开源跨平台 .NET 邮件客户端库,它基于 MimeKit 并针对移动设备进行了优化。您可以在您的应用程序中轻松使用。您可以从here下载。

                      MimeMessage mailMessage = new MimeMessage();
                      mailMessage.From.Add(new MailboxAddress(fromName, from@address.com));
                      mailMessage.Sender = new MailboxAddress(senderName, sender@address.com);
                      mailMessage.To.Add(new MailboxAddress(emailid, emailid));
                      mailMessage.Subject = subject;
                      mailMessage.ReplyTo.Add(new MailboxAddress(replyToAddress));
                      mailMessage.Subject = subject;
                      var builder = new BodyBuilder();
                      builder.TextBody = "Hello There";           
                      try
                      {
                          using (var smtpClient = new SmtpClient())
                          {
                              smtpClient.Connect("HostName", "Port", MailKit.Security.SecureSocketOptions.None);
                              smtpClient.Authenticate("user@name.com", "password");
      
                              smtpClient.Send(mailMessage);
                              Console.WriteLine("Success");
                          }
                      }
                      catch (SmtpCommandException ex)
                      {
                          Console.WriteLine(ex.ToString());              
                      }
                      catch (Exception ex)
                      {
                          Console.WriteLine(ex.ToString());                
                      }              
      

      【讨论】:

        【解决方案6】:

        检查一下....它有效

        http://www.aspnettutorials.com/tutorials/email/email-aspnet2-csharp/

        using System;
        using System.Data;
        using System.Configuration;
        using System.Web;
        using System.Web.Security;
        using System.Web.UI;
        using System.Web.UI.WebControls;
        using System.Web.UI.WebControls.WebParts;
        using System.Web.UI.HtmlControls;
        using System.Net.Mail;
        
        public partial class _Default : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
        
            }
        
            protected void btnSubmit_Click(object sender, EventArgs e)
            {
                try
                {
                    MailMessage message = new MailMessage(txtFrom.Text, txtTo.Text, txtSubject.Text, txtBody.Text);
                    SmtpClient emailClient = new SmtpClient(txtSMTPServer.Text);
                    emailClient.Send(message);
                    litStatus.Text = "Message Sent";
                }
                catch (Exception ex)
                {
                    litStatus.Text=ex.ToString();
                }
            }
        }
        

        【讨论】:

        【解决方案7】:

        只传参数 喜欢 body - 来自客户的内容(查询)
        主题 - 邮件主题中定义的主题
        用户名 - 没有任何名称
        邮件 - 邮件(必填)

           public static bool SendMail(String body, String subject, string username, String mail)
            {
                bool isSendSuccess = false;
                try
                {
                    var fromEmailAddress = ConfigurationManager.AppSettings["FromEmailAddress"].ToString();
                    var fromEmailDisplayName = ConfigurationManager.AppSettings["FromEmailDisplayName"].ToString();
                    var fromEmailPassword = ConfigurationManager.AppSettings["FromEmailPassword"].ToString();
                    var smtpHost = ConfigurationManager.AppSettings["SMTPHost"].ToString();
                    var smtpPort = ConfigurationManager.AppSettings["SMTPPort"].ToString();
        
        
                    MailMessage message = new MailMessage(new MailAddress(fromEmailAddress, fromEmailDisplayName),
                        new MailAddress(mail, username));
                    message.Subject = subject;
                    message.IsBodyHtml = true;
                    message.Body = body;
        
                    var client = new SmtpClient();
                    client.UseDefaultCredentials = false;
                    client.Credentials = new NetworkCredential(fromEmailAddress, fromEmailPassword);
                    client.Host = smtpHost;
                    client.EnableSsl = false;
                    client.Port = !string.IsNullOrEmpty(smtpPort) ? Convert.ToInt32(smtpPort) : 0;
                    client.Send(message);
                    isSendSuccess = true;
                }
                catch (Exception ex)
                {
                    throw (new Exception("Mail send failed to loginId " + mail + ", though registration done."+ex.ToString()+"\n"+ex.StackTrace));
                }
        
                return isSendSuccess;
            }
        

        如果您使用 go daddy 服务器这项工作。在 web.config 中添加这个

          <appSettings>
            ---other ---setting
        
            <add key="FromEmailAddress" value="myemail@gmail.com" />
            <add key="FromEmailDisplayName" value="anyname" />
            <add key="FromEmailPassword" value="mypassword@" />
            <add key="SMTPHost" value="relay-hosting.secureserver.net" />
            <add key="SMTPPort" value="25" />
        
        </appSettings>
        

        如果您使用的是 localhost 或 vps 服务器,请将此配置更改为此

         <appSettings>
            ---other ---setting
        
            <add key="FromEmailAddress" value="myemail@gmail.com" />
            <add key="FromEmailDisplayName" value="anyname" />
            <add key="FromEmailPassword" value="mypassword@" />
            <add key="SMTPHost" value="smtp.gmail.com" /> 
            <add key="SMTPPort" value="587" />
        </appSettings>
        

        修改代码

                  client.EnableSsl = true;
        

        如果您使用的是 gmail,请启用安全应用。使用此链接 https://myaccount.google.com/lesssecureapps?pli=1&rapt=AEjHL4Pd6h3XxE663Flvd-FfeRXxW_eNrIsGTBlZklgkAHZEeuHvheCQuZ1-djB9uIWaB-2EV7hyLCU0dWKA7D0JzYKe4ZRkuA

        【讨论】:

          【解决方案8】:
              using System;
              using System.Collections.Generic;
              using System.Linq;
              using System.Web;
              using System.Globalization;
              using System.Text.RegularExpressions;
              
              /// <summary>
              /// Summary description for RegexUtilities
              /// </summary>
              public class RegexUtilities
              {
                  bool InValid = false;
              
                  public bool IsValidEmail(string strIn)
                  {
                      InValid = false;
                      if (String.IsNullOrEmpty(strIn))
                          return false;
              
                      // Use IdnMapping class to convert Unicode domain names.
                      strIn = Regex.Replace(strIn, @"(@)(.+)$", this.DomainMapper);
                      if (InValid)
                          return false;
              
                      // Return true if strIn is in valid e-mail format. 
                      return Regex.IsMatch(strIn, @"^(?("")(""[^""]+?""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" + @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9]{2,17}))$",
                             RegexOptions.IgnoreCase);
                  }
              
                  private string DomainMapper(Match match)
                  {
                      // IdnMapping class with default property values.
                      IdnMapping idn = new IdnMapping();
              
                      string domainName = match.Groups[2].Value;
                      try
                      {
                          domainName = idn.GetAscii(domainName);
                      }
                      catch (ArgumentException)
                      {
                          InValid = true;
                      }
                      return match.Groups[1].Value + domainName;
                  }
              
              }
          
          
          
           private void GetSendEmInfo()
              {
                  #region For Get All Type Email Informations..!!
                  IPL.DoId = ddlName.SelectedValue;
                  DataTable dt = IdBL.GetEmailS(IPL);
                  if (dt.Rows.Count > 0)
                  {
                      hid_MailId.Value = dt.Rows[0]["MailId"].ToString();
                      hid_UsedPName.Value = dt.Rows[0]["UName"].ToString();
                      hid_EmailSubject.Value = dt.Rows[0]["EmailSubject"].ToString();
                      hid_EmailBody.Value = dt.Rows[0]["EmailBody"].ToString();
                      hid_EmailIdName.Value = dt.Rows[0]["EmailIdName"].ToString();
                      hid_EmPass.Value = dt.Rows[0]["EPass"].ToString();
                      hid_SeName.Value = dt.Rows[0]["SenName"].ToString();
                      hid_TNo.Value = dt.Rows[0]["TeNo"].ToString();
                      hid_EmaLimit.Value = dt.Rows[0]["EmailLimit"].ToString();
                      hidlink.Value = dt.Rows[0][link"].ToString();
                  }
                  #endregion
          
                  #region For Set Some Local Variables..!!
                  int StartLmt, FinalLmt, SendCurrentMail;
                  StartLmt = FinalLmt = SendCurrentMail = 0;
                  bool Valid_LimitMail;
                  Valid_LimitMail = true;
                  /**For Get Finalize Limit For Send Mail**/
                  FinalLmt = Convert.ToInt32(hid_EmailmaxLimit.Value);
                  #region For Check Email Valid Limits..!!
                  if (FinalLmt > 0)
                  {
                      Valid_LimitMail = true;
                  }
                  else
                  {
                      Valid_LimitMail = false;
                  }
                  #endregion
                  /**For Get Finalize Limit For Send Mail**/
                  #endregion
          
                  if (Valid_LimitMail == true)
                  {
                      #region For Send Current Email Status..!!
                      bool EmaiValid;
                      string CreateFileName;
                      string retmailflg = null;
                      EmaiValid = false;
                      #endregion
          
                      #region For Set Start Limit And FinalLimit Send No Of Email..!!
                      mPL.SendDate = DateTime.Now.ToString("dd-MMM-yyyy");
                      DataTable dtsendEmail = m1BL.GetEmailSendLog(mPL);
                      if (dtsendEmail.Rows.Count > 0)
                      {
                          StartLmt = Convert.ToInt32(dtsendEmail.Rows[0]["SendNo_Of_Email"].ToString());
                      }
                      else
                      {
                          StartLmt = 0;
                      }
                      #endregion
          
                      #region For Find Grid View Controls..!!
                      for (int i = 0; i < GrdEm.Rows.Count; i++)
                      {
                          #region For Find Grid view Controls..!!
                          CheckBox Chk_SelectOne = (CheckBox)GrdEmp.Rows[i].FindControl("chkSingle");
                          Label lbl_No = (Label)GrdEmAtt.Rows[i].FindControl("lblGrdCode");
                          lblCode.Value = lbl_InNo.Text;
          
                          Label lbl_EmailId = (Label)GrdEomAtt.Rows[i].FindControl("lblGrdEmpEmail");
          
                          #endregion
          
                          /**Region For If Check Box Checked Then**/
                          if (Chk_SelectOne.Checked == true)
                          {
                              if (!string.IsNullOrEmpty(lbl_EmailId.Text))
                              {
                                  #region For When Check Box Checked..!!
                                  /**If Start Limit Less Or Equal To Then Condition Performs**/
                                  if (StartLmt < FinalLmt)
                                  {
                                      StartLmt = StartLmt + 1;
                                  }
                                  else
                                  {
                                      Valid_LimitMail = false;
                                      EmaiValid = false;
                                  }
                                  /**End Region**/
                                  string[] SplitClients_Email = lbl_EmailId.Text.Split(',');
                                  string Send_Email, Hold_Email;
                                  Send_Email = Hold_Email = "";
          
                                  int CountEmail;/**Region For Count Total Email**/
                                  CountEmail = 0;/**First Time Email Counts Zero**/
          
                                  Hold_Email = SplitClients_Email[0].ToString().Trim().TrimEnd().TrimStart().ToString();
                                  /**Region For If Clients Have One Email**/
                                  #region For First Emails Send On Client..!!
                                  if (SplitClients_Email[0].ToString() != "")
                                  {
                                      if (EmailRegex.IsValidEmail(Hold_Email))
                                      {
                                          Send_Email = Hold_Email;
                                          CountEmail = 1;
                                          EmaiValid = true;
                                      }
                                      else
                                      {
                                          EmaiValid = false;
                                      }
                                  }
                                  #endregion
                                  /**Region For If Clients Have One Email**/
                                  /**Region For If Clients Have Two Email**/
          
                                  /**Region For If Clients Have Two Email**/
                                  if (EmaiValid == true)
                                  {
                                      #region For Create Email Body And Create File Name..!!
                                      //fofile = Server.MapPath("PDFs");
                                      fofile = Server.MapPath("~/vvv/vvvv/") + "/";
                                      CreateFileName = lbl_INo.Text.ToString() + "_1" + ".Pdf";/**Create File Name**/
                                      string[] orimail = Send_Email.Split(',');
                                      string Billbody, TempInvoiceId;
                                      // DateTime dtLstdate = new DateTime(Convert.ToInt32(txtYear.Text), Convert.ToInt32(ddlMonth.SelectedValue), 16);
          
                                      //  DateTime IndtLmt = dtLstdate.AddMonths(1);
                                      TempInvoiceId = "";
          
                                      //byte[] Buffer = Encrypt.Encryptiondata(lbl_InvoiceNo.Text.ToString());
                                      //TempInvoiceId = Convert.ToBase64String(Buffer);
          
          
                                      #region Create Encrypted Path
          
          
                                      byte[] EncCode = Encrypt.Encryptiondata(lbl_INo.Text);
                                      hidEncrypteCode.Value = Convert.ToBase64String(EncECode);
                                      #endregion
          
                                  
          
                                      //#region Create Email Body !!
                                      //body = hid_EmailBody.Value.Replace("@greeting", lbl_CoName.Text).Replace("@free", hid_ToNo.Value).Replace("@llnk", "<a style='font-family: Tahoma; font-size: 10pt; color: #800000; font-weight: bold' href='http://1ccccc/ccc/ccc/ccc.aspx?EC=" + hidEncryptedCode.Value+ "' > C cccccccc </a>");
                                    
          
                                      body = hid_EmailBody.Value.Replace("@greeting", "Hii").Replace("@No", hid_No.Value);/*For Mail*/
                                      //#endregion
          
          
          
                                      #region For Email Sender Informations..!!
                                      for (int j = 0; j < CountEmail; j++)
                                      {
                                          //if (File.Exists(fofile + "\\" + CreateFileName))
                                          //{
                                          #region
                                          lbl_EmailId.Text = orimail[j];
                                          retmailflg = "";
          
                                          /**Region For Send Email For Clients**/
                                          //retmailflg = SendPreMail("Wp From " + lbl_CName.Text + "", body, lbl_EmailId.Text, lbl_IeNo.Text, hid_EmailIdName.Value, hid_EmailPassword.Value);
                                          retmailflg = SendPreMail(hid_EmailSubject.Value, Body, lbl_EmailId.Text, lbl_No.Text, hid_EmailIdName.Value, hid_EmailPassword.Value);
                                          /**End Region**/
          
                                          /**Region For Create Send Email Log  When Email Send Successfully**/
                                          if (retmailflg == "True")
                                          {
                                              SendCurrentMail = Convert.ToInt32(SendCurrentMail) + 1;
                                              StartLmt = Convert.ToInt32(StartLmt) + 1;
          
                                              if (SendCurrentMail > 0)
                                              {
                                                  CreateEmailLog(lbl_InNo.Text, StartLmt, hid_EmailIdName.Value, lbl_EmailId.Text);
                                                  
                                              }
                                          }
                                          
          
                                          /**End Region**/
                                          #endregion
                                          //}
                                      }
                                      #endregion
                                  }
                                  #endregion
                              }
                          }
                          /**End Region**/
                      }
                      #endregion
          
                  }
                 
              }
              private void CreateEmailLog(string UniqueId, int StartLmt, string FromEmailId, string TotxtEmailId)
              {
                  FPL.EmailId_From = FromEmailId;
                  FPL.To_EmailId = TotxtEmailId;
                  FPL.SendDate = DateTime.Now.ToString("dd-MMM-yyyy");
                  FPL.EmailUniqueId = UniqueId;
                  FPL.SendNo_Of_Email = StartLmt.ToString();
                  FPL.LoginUserId = Session["LoginUserId"].ToString();
                  int i = FBL.InsertEmaDoc(FPL);
              }
          
              public string SendPreMail(string emsub, string embody, string EmailId, string FileId, string EmailFromId, string Password)
              {
                  string retval = "False";
                  try
                  {
                      string emailBody, emailSubject, emailToList, emailFrom,
                      accountPassword, smtpServer;
                      bool enableSSL;
                      int port;
          
                      emailBody = embody;
                      emailSubject = emsub;
                      emailToList = EmailId;
                      emailFrom = EmailFromId;
                      accountPassword = Password;
                      smtpServer = "smtp.gmail.com";
                      enableSSL = true;
                      port = 587;
          
                      string crefilename;
                      string fofile;
                      fofile = Server.MapPath("PDF");
                      crefilename = FileId + ".Pdf";
          
                      string[] att = { crefilename };
          
                      string retemail, insertqry;
                      retemail = "";
          
                      retemail = SendEmail(emailBody, emailSubject, emailFrom, emailToList, att, smtpServer, enableSSL, accountPassword, port);
          
                      if (retemail == "True")
                      {
          
                          retval = retemail;
                      }
                  }
                  catch
                  {
                      retval = "False";
                  }
                  finally
                  {
          
                  }
                  return retval;
              }
          
              public string SendEmail(string emailBody, string emailSubject, string emailFrom, string emailToList, string[] attachedFiles, string smtpIPAddress, bool enableSSL, string accountPassword, int port)
              {
                  MailMessage mail = new MailMessage();
                  string retflg;
                  retflg = "False";
                  try
                  {
                      mail.From = new MailAddress(emailFrom);
                      if (emailToList.Contains(";"))
                      {
                          emailToList = emailToList.Replace(";", ",");
                      }
                      mail.To.Add(emailToList);
          
                      mail.Subject = emailSubject;
                      mail.IsBodyHtml = true;
                      mail.Body = emailBody;
          
          
                      SmtpClient smtp = new SmtpClient();
                      smtp.Host = "smtp.gmail.com";
                      smtp.EnableSsl = true;
                      NetworkCredential NetworkCred = new NetworkCredential(emailFrom, accountPassword);
                      smtp.UseDefaultCredentials = true;
                      smtp.Credentials = NetworkCred;
                      smtp.Port = 587;
                      smtp.Send(mail);
                      retflg = "True";
          
                  }
                  catch
                  {
                      retflg = "False";
                  }
                  finally
                  {
                      mail.Dispose();
                  }
                  return retflg;
              }
          

          【讨论】:

            【解决方案9】:

            如果您想在 razor 中生成电子邮件正文,可以使用Mailzory。另外,你可以从here下载nuget包。

            // template path
            var viewPath = Path.Combine("Views/Emails", "hello.cshtml");
            // read the content of template and pass it to the Email constructor
            var template = File.ReadAllText(viewPath);
            
            var email = new Email(template);
            
            // set ViewBag properties
            email.ViewBag.Name = "Johnny";
            email.ViewBag.Content = "Mailzory Is Funny";
            
            // send email
            var task = email.SendAsync("mailzory@outlook.com", "subject");
            task.Wait()
            

            【讨论】:

              【解决方案10】:

              据此:

              SmtpClient 及其网络类型设计不佳,我们强烈 建议您使用https://github.com/jstedfast/MailKithttps://github.com/jstedfast/MimeKit 代替。

              参考:https://docs.microsoft.com/en-us/dotnet/api/system.net.mail.smtpclient?view=netframework-4.8

              最好用MailKit发邮件:

              var message = new MimeMessage ();
                          message.From.Add (new MailboxAddress ("Joey Tribbiani", "joey@friends.com"));
                          message.To.Add (new MailboxAddress ("Mrs. Chanandler Bong", "chandler@friends.com"));
                          message.Subject = "How you doin'?";
              
                          message.Body = new TextPart ("plain") {
                              Text = @"Hey Chandler,
              I just wanted to let you know that Monica and I were going to go play some paintball, you in?
              -- Joey"
                          };
              
                          using (var client = new SmtpClient ()) {
                              // For demo-purposes, accept all SSL certificates (in case the server supports STARTTLS)
                              client.ServerCertificateValidationCallback = (s,c,h,e) => true;
              
                              client.Connect ("smtp.friends.com", 587, false);
              
                              // Note: only needed if the SMTP server requires authentication
                              client.Authenticate ("joey", "password");
              
                              client.Send (message);
                              client.Disconnect (true);
                          }
              

              【讨论】:

                【解决方案11】:

                Google 可能会阻止来自不使用现代安全标准的某些应用或设备的登录尝试。由于这些应用和设备更容易被入侵,因此阻止它们有助于确保您的帐户更安全。

                一些不支持最新安全标准的应用示例包括:

                1. 安装 iOS 6 或更低版本的 iPhone 或 iPad 上的邮件应用
                2. Windows 手机上 8.1 版本之前的邮件应用
                3. 某些桌面邮件客户端,例如 Microsoft Outlook 和 Mozilla Thunderbird

                因此,您必须在您的 Google 帐户中启用不太安全的登录(或不太安全的应用访问权限)。

                登录谷歌账号后,前往:

                https://www.google.com/settings/security/lesssecureapps 要么 https://myaccount.google.com/lesssecureapps

                在 C# 中,您可以使用以下代码:

                        MimeMessage message = new MimeMessage();
                        BodyBuilder Attachmint = new BodyBuilder();
                        message.From.Add(new MailboxAddress("name sender", "Mail From"));
                        message.To.Add(MailboxAddress.Parse("Mail To"));
                        message.Subject = Subject;
                        message.Body = new TextPart("plain")
                        {
                            Text = tex_body.Text + Massage
                        };
                
                        Attachmint.Attachments.Add("Attatchment Path");
                        message.Body = Attachmint.ToMessageBody();
                
                        SmtpClient client = new SmtpClient();
                        client.Connect("smtp.gmail.com", 465, true);
                        client.Authenticate("Mail from", "Password mail");
                        client.Send(message);
                

                您可以将邮件从 Gmail 发送到作为 X@PrivetCompany.com 的私人邮箱

                【讨论】:

                  【解决方案12】:
                  MailMessage mm = new MailMessage(txtEmail.Text, txtTo.Text);
                  mm.Subject = txtSubject.Text;
                  mm.Body = txtBody.Text;
                  if (fuAttachment.HasFile)//file upload select or not
                  {
                      string FileName = Path.GetFileName(fuAttachment.PostedFile.FileName);
                      mm.Attachments.Add(new Attachment(fuAttachment.PostedFile.InputStream, FileName));
                  }
                  mm.IsBodyHtml = false;
                  SmtpClient smtp = new SmtpClient();
                  smtp.Host = "smtp.gmail.com";
                  smtp.EnableSsl = true;
                  NetworkCredential NetworkCred = new NetworkCredential(txtEmail.Text, txtPassword.Text);
                  smtp.UseDefaultCredentials = true;
                  smtp.Credentials = NetworkCred;
                  smtp.Port = 587;
                  smtp.Send(mm);
                  Response.write("Send Mail");
                  

                  观看视频:https://www.youtube.com/watch?v=bUUNv-19QAI

                  【讨论】:

                    【解决方案13】:

                    这是最容易测试的脚本。

                    <%@ Import Namespace="System.Net" %> 
                    <%@ Import Namespace="System.Net.Mail" %> 
                    
                    <script language="C#" runat="server"> 
                        protected void Page_Load(object sender, EventArgs e) 
                        { 
                           //create the mail message 
                            MailMessage mail = new MailMessage(); 
                    
                            //set the addresses 
                            mail.From = new MailAddress("From email account"); 
                            mail.To.Add("To email account"); 
                    
                            //set the content 
                            mail.Subject = "This is a test email from C# script"; 
                            mail.Body = "This is a test email from C# script"; 
                            //send the message 
                             SmtpClient smtp = new SmtpClient("mail.domainname.com"); 
                    
                             NetworkCredential Credentials = new NetworkCredential("to email account", "Password"); 
                             smtp.Credentials = Credentials;
                             smtp.Send(mail); 
                             lblMessage.Text = "Mail Sent"; 
                        } 
                    </script> 
                    <html> 
                    <body> 
                        <form runat="server"> 
                            <asp:Label id="lblMessage" runat="server"></asp:Label> 
                        </form> 
                    </body>
                    

                    【讨论】:

                    • 为什么会选择把它放在视图中而不让控制器处理呢?
                    • 刚刚问了关于通过 ASP.NET C# 发送电子邮件的问题。没有提到在脚本中设置控制器。
                    猜你喜欢
                    • 2012-07-27
                    • 1970-01-01
                    • 2011-03-20
                    • 2013-06-27
                    • 1970-01-01
                    • 2014-10-31
                    • 2011-11-21
                    • 1970-01-01
                    相关资源
                    最近更新 更多