如何使用C#中的名称发送多个电子邮件地址

时间:2014-12-05 10:23:27

标签: c# email

如何使用C#发送多个带有名称的电子邮件地址?目前,我需要从数据库中加载名称和电子邮件地址并发送。

  1. 所以我应该先创建一个字符串数组来存储名称和电子邮件地址吗?

  2. 然后我如何发送电子邮件?必须为多个邮件地址使用MailMessages()或MailAddress吗?

  3. 我的代码

    while (sdrReader.Read())
    {      
        ReceiverName = sdrReader["Name"].ToString();
        ReceiverEmail = sdrReader["EmailAddress"].ToString();           
    }
    

    // Mail to Add,在这里我想获取多个电子邮件名称和地址,然后发送它们。

    mail.To.Add(new MailAddress(ReceiverEmail, ReceiverName));
    
    
    
    sSQL = @"SELECT * FROM EmailSystem";
    
                try
                {
                    scConnection.Open();
                    scCommand = new SqlCommand(sSQL, scConnection);
                    sdrReader = scCommand.ExecuteReader();
    
                    while (sdrReader.Read())
                    {
    
                            ReceiverName = sdrReader["Name"].ToString();
                            ReceiverEmail = sdrReader["EmailAddress"].ToString();
    
                    }
                }
    
    
    
    try
                {
                    // Instance of Mail Server
                    MailMessage mail = new MailMessage();
    
                    // Instance of SMTP Server
                    SmtpClient server = new SmtpClient(smtpAddress);
    
    
                    mail.To.Add(new MailAddress(ReceiverEmail, ReceiverName));            
                }
    

3 个答案:

答案 0 :(得分:1)

这是您可能用来实现目标的草图。我没有触及数据库连接,我希望您检查过可以从数据库中读取数据。如果您有更多问题,请不要犹豫。

// define the body of your mail
var message = new MailMessage
{
    From = new MailAddress("foo@gmail.com", "John Doe"),
    Subject = "Please don't spam me",
    Body = "I will be very angry if you send me spam."
};

// if you don't use gmail, then you have to specify your own settings!!!
var client = new SmtpClient("smtp.gmail.com", 587)
{
    EnableSsl = true,
    Credentials = new NetworkCredential("foo@gmail.com", "superPassword")
};

// I skipped the creation of connection and command.
// Don't forget to call Dispose when you finish to work with database.
while (sdrReader.Read())
{
    var to = new MailAddress(sdrReader["EmailAddress"].ToString(),
                             sdrReader["Name"].ToString());
    message.To.Add(to);
}

client.Send(message);

答案 1 :(得分:0)

您可以自动化Microsoft Outlook以编程方式发送电子邮件。有关详细信息,请参阅Using Automation to Send a Microsoft Outlook Message

答案 2 :(得分:0)

使用数据集或数据表而不是数据读取器,并为每个值迭代值。

希望以下链接能够为发送批量电子邮件提供更好的指导。

Send bulk email using asp.net and c#

Mass Emailing Functionality with C#, .NET 2.0, and Microsoft® SQL Server 2005 Service Broker