如何将值从textBox发送到邮件?

时间:2018-05-25 11:45:06

标签: c#

我有了制作邮件发件人的想法。我试图寻找解决方案,但没有一个真正起作用,他们被严重解释或甚至可能做到这一点? 所以我基本上有这个if else代码检查它是否为空,如果它不是,它会将值发送给邮件。

using System.Net.Mail; //i think this is what i need?

private void button1_Click(object sender, EventArgs e)
{
    if(string.IsNullOrWhiteSpace(textBox1.Text) && string.IsNullOrWhiteSpace(textBox2.Text))
    {
        MessageBox.Show("You're empty!");
    }
    else if(Int32.Parse(textBox1.Text) != 0)
    {
        // send text box to mail
    }
    else
    {
        MessageBox.Show("Something went wrong.");
        System.Threading.Thread.Sleep(2000);
        MessageBox.Show("Closing");
        System.Threading.Thread.Sleep(1000);
        this.Close();
    }
}

有人愿意指导我正确的方向,或者可能帮我解释一下如何做到这一点?

2 个答案:

答案 0 :(得分:1)

Try this :
private void button1_Click(object sender, EventArgs e)
{
sendMailToAdmin(textbox1.Text,textbox2.text);
}

protected void sendMailToAdmin(string uname, string email)
{
    MailMessage myMsg = new MailMessage();
    myMsg.From = new MailAddress("****@mail.com");
    myMsg.To.Add(email);
    myMsg.Subject = "New User Email ";
    myMsg.Body = "New User Information\n\nUser Name: " + uname + "\nEmail : " + email;

    // your remote SMTP server IP.
    SmtpClient smtp = new SmtpClient();
    smtp.Host = "smtp.gmail.com";
    smtp.Port = 587;
    smtp.Credentials = new System.Net.NetworkCredential("****@mail.com", "pass***");
    smtp.EnableSsl = true;
    smtp.Send(myMsg);
}

答案 1 :(得分:0)

您可以将textBox1.Text作为电子邮件正文,如下所示:

mail.From = new MailAddress(emailaddress);
mail.To.Add(recipient);
mail.Subject = "Test Mail";

mail.Body = textBox1.Text; // sets the body to the text box's content

SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential(emailaddress, password);
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);

System.Windows.Forms.MessageBox.Show("Mail sent");