Azure WebJob用于:从SQL创建CSV文件并通过电子邮件作为附件发送

时间:2018-11-23 17:08:00

标签: sql azure azure-sql-database azure-web-sites azure-webjobs

到目前为止,设法做到

  1. 通过Visual Studio创建一个C#Azure WebJob项目并将其发布到Web应用程序中,
  2. 连接到Azure SQL数据库并执行SQL查询(通过SqlDataReader)
  3. 将SqlDataReader结果添加到电子邮件正文中
  4. 发送电子邮件

除上述内容外,在上述第3点至第4点之间,我需要

  1. 创建.CSV文件
  2. 从SqlDataReader中填充.CSV文件
  3. 通过电子邮件将.CSV文件作为附件发送

从SqlDataReader填充CSV的结果集如下:

asdasd@gmail.com,2018年11月19日
asdasdasd@gmail.com,11/19/2018
asdasdasasdas@live.co.uk,2018年11月19日
asdasddsa@hotmail.com,2018年11月19日
asdasd@hotmail.com,11/19/2018
asdasddsa@hotmail.com,2018年11月19日
asdasasd@gmail.com,11/18/2018

以下是我到目前为止的内容:

    public static void Main(string[] args)
    {
        SmtpClient smtp = new SmtpClient();
        int SMTP_PORT = 587; 
        Int32.TryParse(ConfigurationManager.AppSettings["SMTP_PORT"], out SMTP_PORT);
        smtp.Port = SMTP_PORT;
        smtp.Credentials = new NetworkCredential(ConfigurationManager.AppSettings["SMTP_USERNAME"], ConfigurationManager.AppSettings["SMTP_PASSWORD"]);
        smtp.Host = ConfigurationManager.AppSettings["SMTP_HOST"];
        string mailFrom = ConfigurationManager.AppSettings["SMTP_MAIL_FROM"];
        string mailSubject = ConfigurationManager.AppSettings["SMTP_MAIL_SUBJECT"];  

        using (SqlConnection connection = new SqlConnection(ConfigurationManager.AppSettings["AzureDBConnString"]))
        {
            connection.Open();

            var queryString = @"SELECT * FROM MyTable WHERE Status = 1";

            using (SqlCommand command = new SqlCommand(queryString, connection))
            {
                command.CommandTimeout = 120;
                SqlDataReader reader = command.ExecuteReader();

                if (reader.HasRows)
                {
                    while (reader.Read()) // loop each user and send email
                    {
                        bool emailSentSuccess = true;
                        using (MailMessage mail = new MailMessage())
                        {
                            try
                            {
                                mail.From = new MailAddress(mailFrom);
                                mail.To.Add(new MailAddress(reader["EmailAddress"].ToString()));
                                mail.IsBodyHtml = true;
                                mail.Subject = mailSubject;
                                mail.Body = reader["EmailBody"].ToString();
                                smtp.Send(mail);
                            }
                            catch (Exception ex)
                            {
                                emailSentSuccess = false;
                            }
                        }
                    }
                }
            }
        }
    }

问题:如何获得5、6、7分?

1 个答案:

答案 0 :(得分:0)

您可以在SqlCommand中引用以下代码。

using (SqlCommand command = new SqlCommand(queryString, connection))
{
    command.CommandTimeout = 120;
    SqlDataReader reader = command.ExecuteReader();
    if (reader.HasRows)
    {
        StringBuilder sb = new StringBuilder();
        List<string> columnNames = new List<string>();
        List<string> rows = new List<string>();
        for (int i = 0; i < reader.FieldCount; i++)
        {
            string tmpColumnName = reader.GetName(i);
            columnNames.Add(tmpColumnName);
        } 
        sb.Append(string.Join(",", columnNames.ToArray())).Append("\r\n");
        List<string> currentRow = new List<string>();
        while (reader.Read())
        {
            for (int i = 0; i < reader.FieldCount; i++)
            {
                object item = reader[i];
                sb.Append(item.ToString().Replace(",", ";") + ',');
            }
            sb.Append("\r\n");
        }
        bool emailSentSuccess = true;
        using (MailMessage mail = new MailMessage())
        {
            try
            {
                using (MemoryStream stream = new MemoryStream(Encoding.ASCII.GetBytes(sb.ToString())))
                {
                    Attachment attachment = new Attachment(stream, new ContentType("text/csv"));
                    attachment.Name = "hello.csv";
                    mail.Attachments.Add(attachment);
                    mail.From = new MailAddress(mailFrom);
                    mail.To.Add(new MailAddress(reader["EmailAddress"].ToString()));
                    mail.IsBodyHtml = true;
                    mail.Subject = mailSubject;
                    mail.Body = reader["EmailBody"].ToString();
                    smtp.Send(mail);
                }
            }
            catch (Exception ex)
            {
                emailSentSuccess = false;
            }
        }
    }
}

我测试的输出如下:

enter image description here