【问题标题】:Using System.Net.Mail to send email from Database list of user使用 System.Net.Mail 从用户的数据库列表发送电子邮件
【发布时间】:2017-01-20 06:04:58
【问题描述】:

我有以下电子邮件功能,可向用户列表发送电子邮件。我用message.To.Add(new MailAddress("UserList@email.com"))的方法添加用户:

Using System.Net.Mail

protected void SendMail()
{     

    //Mail notification
    MailMessage message = new MailMessage();
    message.To.Add(new MailAddress("UserList@email.com"));
    message.Subject = "Email Subject ";
    message.Body = "Email Message";
    message.From = new MailAddress("MyEmail@mail.com");

    // Email Address from where you send the mail
    var fromAddress = "MyEmail@mail.com";

    //Password of your mail address
    const string fromPassword = "password";

    // smtp settings
    var smtp = new System.Net.Mail.SmtpClient();
    {
        smtp.Host = "smtp.mail.com";
        smtp.EnableSsl = true;
        smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
        smtp.Credentials = new NetworkCredential(fromAddress, fromPassword);
        smtp.Timeout = 20000;
    }
    // Passing values to smtp object        
    smtp.Send(message);
}

但是,我怎样才能连接到 SQL-Server Db 并从表中获取用户列表,而不是从这个函数中获取?谢谢您的帮助!

【问题讨论】:

  • 数据库不止一种,这个问题也不止一种。请一次问一个问题。为什么不实际尝试实现与数据库表的连接,并提出一个真正的问题?
  • 第一个问题我假设是的,第二个问题:如何在这段代码中实现 SqlConnection (SQL Server)?谢谢!
  • @Jacman 我会研究“从 SQL 发送邮件”。有一个系统存储过程实际上是从 SQL 而不是 .NET 内部进行发送的。至于您关于在代码中实现数据库连接的问题......没有任何神奇的方法可以为此添加数据库连接。简单地添加一个连接不会做你想做的事情。例如,您可以打开一个数据阅读器并为阅读器返回的每一行运行此函数。
  • 您想要做的实际上非常简单,您需要创建一个方法或类来为您完成大部分工作,并且在发送电子邮件时您需要创建一个方法来填充List<string> 的用户电子邮件并有一个分隔符 | 例如然后您可以基于一个简单的方法构建 SendTo 列表我可以向您发布一个关于如何构建电子邮件功能的简单方法,您需要执行代码使用 C# 从数据库中返回电子邮件地址并不难。如果您想要发送电子邮件的示例,请告诉我..

标签: c# sql asp.net mailmessage


【解决方案1】:

我自己以最简单的方式解决了这个问题。我希望这对其他人有帮助。感谢所有积极响应、有思考能力和使用常识的人。

Using System.Net.Mail

protected void SendMail()
{     

    //Mail notification
    MailMessage message = new MailMessage();
    message.Subject = "Email Subject ";
    message.Body = "Email Message";
    message.From = new MailAddress("MyEmail@mail.com");

    // Email Address from where you send the mail
    var fromAddress = "MyEmail@mail.com";

    //Password of your mail address
    const string fromPassword = "password";

    // smtp settings
    var smtp = new System.Net.Mail.SmtpClient();
    {
    smtp.Host = "smtp.mail.com";
    smtp.EnableSsl = true;
    smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
    smtp.Credentials = new NetworkCredential(fromAddress, fromPassword);
    smtp.Timeout = 20000;
    }
    SqlCommand cmd = null;
    string connectionString = ConfigurationManager.ConnectionStrings["DbConnectionString"].ConnectionString;
    string queryString = @"SELECT EMAIL_ADDRESS FROM EMAIL WHERE EMAIL_ADDRESS = EMAIL_ADDRESS";

    using (SqlConnection connection =
               new SqlConnection(connectionString))
    {
        SqlCommand command =
            new SqlCommand(queryString, connection);
        connection.Open();
        cmd = new SqlCommand(queryString);
        cmd.Connection = connection;

        SqlDataReader reader = cmd.ExecuteReader();

        // Call Read before accessing data.
        while (reader.Read())
        {

            var to = new MailAddress(reader["EMAIL_ADDRESS"].ToString());
            message.To.Add(to);

        }

        // Passing values to smtp object        
        smtp.Send(message);

        // Call Close when done reading.
        reader.Close();
    }
}

【讨论】:

    【解决方案2】:

    您可以在当前项目中创建此实用程序.cs 文件并粘贴以下代码,看看它是多么容易阅读

    public class utilities
    {  
    
        public static string ConnectionString
        {
            get { return ConfigurationManager.ConnectionStrings["DbConn"].ConnectionString; } //change dbconn to whatever your key is in the config file
        } 
    
        public static string EmailRecips
        {
            get
            {
                return ConfigurationManager.AppSettings["EmailRecips"];//in the config file it would look like this <add key="EmailRecips" value="personA@SomeEmail.com|PersonB@SomeEmail.com|Person3@SomeEmail.com"/>
            }
        }   
    
        public static string EmailHost //add and entry in the config file for EmailHost 
        {
            get
            {
                return ConfigurationManager.AppSettings["EmailHost"];
            }
        }
    
        public static void SendEmail(string subject, string body) //add a third param if you want to pass List<T> of Email Address then use `.Join()` method to join the List<T> with a `emailaddr + | emailAddr` etc.. the Join will append the `|` for you if tell look up how to use List<T>.Join() Method
        {
            using (var client = new SmtpClient(utilities.EmailHost, 25)) 
            using (var message = new MailMessage()
            {
                From = new MailAddress(utilities.FromEmail),
                Subject = subject,
                Body = body
            })
            {
                //client.EnableSsl = true; //uncomment if you really use SSL
                //client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
                //client.Credentials = new NetworkCredential(fromAddress, fromPassword);    
    
                foreach (var address in utilities.EmailRecips.Split(new[] { "|" }, StringSplitOptions.RemoveEmptyEntries))
                    message.To.Add(address);
                client.Send(message);
            }
        }
    }
    

    //如果您想传递一个列表并加入一个管道分隔字符串的字符串以在 .Split 函数中使用,那么您可以更改方法签名以获取一个字符串并将其传递给电子邮件,例如

    var emailList = string.Join("|", YourList<T>);
    

    //那么新的邮件函数签名应该是这样的

    public static void SendEmail(string subject, string body, string emailList)
    

    //然后你会用这个替换.Split方法

    foreach (var address in emailList.Split(new[] { "|" }, StringSplitOptions.RemoveEmptyEntries))
    

    【讨论】:

      【解决方案3】:

      您可以做很多事情来优化和概括下面的代码 - 在做您想做的事情时,它会尽可能接近您的代码。由您决定如何连接到您的数据库并获取 DataReader.Read()。试试看——如果你遇到困难,问一些具体的问题。

      Using System.Net.Mail
      
      protected void SendMail()
      {     
      Dictionary<string,string> recipients = new Dictionary<string,string>
      //--select FirstName, Email form MyClients
      //while reader.Read(){
        recipients.Add(Convert.ToString(reader[0]),Convert.ToString(reader[1]));//adds from user to dictionary
      //}
      
      
      //Mail notification
      
      
      foreach(KeyValuePair<string,string> kvp in recipients){
          MailMessage message = new MailMessage();
          message.To.Add(new MailAddress(kvp.Value));
      
      
          message.Subject = "Hello,  "+kvp.Key;
          message.Body = "Email Message";
          message.From = new MailAddress("MyEmail@mail.com");
      
          // Email Address from where you send the mail
          var fromAddress = "MyEmail@mail.com";
      
          //Password of your mail address
          const string fromPassword = "password";
      
          // smtp settings
          var smtp = new System.Net.Mail.SmtpClient();
          {
              smtp.Host = "smtp.mail.com";
              smtp.EnableSsl = true;
              smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
              smtp.Credentials = new NetworkCredential(fromAddress, fromPassword);
              smtp.Timeout = 20000;
          }
          // Passing values to smtp object        
          smtp.Send(message);
        }
      } //This bracket was outside the code box
      

      【讨论】:

      • PS - 我并没有真正查看您提供的代码以确保它可以工作。我假设您复制/粘贴。如果您知道如何添加收件人并遇到错误 - 请回来告诉我们发生了什么。
      • 实际上有一种更简单、更简洁的方法来执行此操作,并且所有 OP 真正需要的是在执行 to 时使用一组分隔的电子邮件地址
      • 请阅读我在// cmets 中的内容,这非常简单,如果您想从数据库中读取,则必须创建一个List&lt;string&gt; of the email addresses only. then from there you can use the .Join()` 方法来使用| 分隔符加入列表,它在我发布的示例中更加清晰,您只需创建返回电子邮件地址列表并循环遍历数据集等的函数。然后将电子邮件地址添加到 List 对象并在调用发送电子邮件功能时添加广告方法 &lt;List&lt;string&gt; emailList 中的最后一个参数作为参数
      • @Shannon 谢谢,我也会试试你的解决方案。
      猜你喜欢
      • 2013-04-02
      • 2011-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-20
      • 1970-01-01
      相关资源
      最近更新 更多