使用System.Net.Mail从数据库的用户列表中发送电子邮件

本文关键字:列表 电子邮件 用户 Net System Mail 数据库 使用 | 更新日期: 2023-09-27 18:06:45

我有以下电子邮件函数,向用户列表发送电子邮件。我用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并从表中获取用户列表,而不是从这个函数?谢谢你的帮助!

使用System.Net.Mail从数据库的用户列表中发送电子邮件

我自己用最简单的方法弄明白了。我希望这对其他人有所帮助。感谢每一个积极回应的人,有能力思考,运用常识。

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();
    }
}

您可以在当前项目中创建这个utilities.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))

您可以做很多事情来优化和泛化下面的代码-它在做您想做的事情时尽可能接近您的代码。如何连接到数据库并获取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