Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send data trough email

I need to send list box items to email. Code is running fine, but when it gets to Send method it fails to send it.

    protected void ProcessButton_Click(object sender, EventArgs e)
    {
        try
        {
            MailMessage mailMessage = new MailMessage();
            mailMessage.To.Add("[email protected]");
            mailMessage.From = new MailAddress("[email protected]");
            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);
        }
    }
like image 886
Nemanja Avatar asked Dec 03 '25 04:12

Nemanja


1 Answers

You can write list in file and send it as attachment (gmail example):

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

        MailMessage message = new MailMessage(new MailAddress("[email protected]"),
            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;
        }
    }

and write this on begining of code:

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

You can choose smpt host adress and port if you want.

like image 125
Jeidoz Avatar answered Dec 05 '25 21:12

Jeidoz