如何通过电子邮件发送数据

时间:2017-04-29 18:28:08

标签: c# asp.net email listbox

我需要将列表框项目发送到电子邮件。代码运行正常,但是当它到达Send方法时,它无法发送它。

    protected void ProcessButton_Click(object sender, EventArgs e)
    {
        try
        {
            MailMessage mailMessage = new MailMessage();
            mailMessage.To.Add("someone@live.com");
            mailMessage.From = new MailAddress("myAdress@live.com");
            mailMessage.Subject = "ASP.NET e-mail test";
            mailMessage.Body = OrderListBox.Items.ToString();
            SmtpClient smtpClient = new SmtpClient("smtp.live.com");
            smtpClient.Send(mailMessage);
            Response.Write("E-mail sent!");
        }
        catch (Exception ex)
        {
            Response.Write("Could not send email - error: " + ex.Message);
        }
    }

1 个答案:

答案 0 :(得分:1)

您可以在文件中编写列表并将其作为附件发送(gmail示例):

protected bool ProcessButton_Click(object sender, EventArgs e)
    {
        SmtpClient client = new SmtpClient();
        client.Host = "smtp.gmail.com";
        client.Port = 587;
        client.Credentials = new NetworkCredential("myEmail@gmail.com", "password");
        //if you have double verification on gmail, then generate and write App Password
        client.EnableSsl = true;

        MailMessage message = new MailMessage(new MailAddress("myEmail@gmail.com"),
            new MailAddress(receiverEmail));
        message.Subject = "Title";
        message.Body = $"Text";

        // Attach file
        Attachment attachment;
        attachment = new Attachment("D:\list.txt");
        message.Attachments.Add(attachment);

        try
        {
            client.Send(message);
            // ALL OK
            return true;
        }
        catch
        {
            //Have problem
            return false;
        }
    }

并在开始代码时写下:

using System.Net;
using System.Net.Mail;

如果需要,您可以选择提示主机地址和端口。