发送邮件的邮箱要先启用SMTP,否则不能发送
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Net.Mail;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnfasong_Click(object sender, EventArgs e)
{
try
{
MailAddress EmailFrom = new MailAddress(txtSend.Text); //发件人邮箱地址
string EmailTo = txtTo.Text; //收件人邮箱地址
string Emailbiaoti = txtbiaoti.Text; //邮件标题
string Emailneirong = txtneirong.Text; //邮件内容
fasong(EmailTo, Emailbiaoti, Emailneirong, EmailFrom);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
public void fasong(string EmailTo, string Emailbiaoti, string Emailneirong, MailAddress EmailFrom)
{
try
{
txtTo.Text = txtTo.Text.Replace(" ", "");//去除空格
txtTo.Text = txtTo.Text.Trim();
MailMessage email = new MailMessage();
email.From = EmailFrom;
email.To.Add(EmailTo);//收件人邮箱地址可以是多个以实现群发
email.Subject = Emailbiaoti;//获取邮件的标题
email.Body = Emailneirong;//获取邮件的内容
email.IsBodyHtml = false; //是否为html格式
email.Priority = MailPriority.Normal; //发送邮件的优先等级
SmtpClient sc = new SmtpClient();//允许使用SMTP协议发送邮件
sc.Host = cbHost.Text;//指定发送邮件的服务器地址
sc.Port = 25;//指定发送邮件端口
sc.DeliveryMethod = SmtpDeliveryMethod.Network;//指定如何发送电子邮件,通过网络发送到SMTP服务器
sc.UseDefaultCredentials = false;//是否随请求一起发送
sc.EnableSsl = false;//安全连接设置
sc.Credentials = new System.Net.NetworkCredential(txtSend.Text, txtSenderPwd.Text); //指定登录服务器的用户名和密码
sc.Send(email);
MessageBox.Show("发送成功!");
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
}
}