这是我一直在制作的代码,我只是测试它是否有效但是有一条错误消息指出“System.FormatException”
我无法理解我遇到了这样的问题。请帮忙
public Mail(string sendMail)
{
this.sendAddress = new MailAddress(sendMail); // exception here
}
public void SetToAddress(string toMail)
{
this.toAddress = new MailAddress(toMail);
}
public string SendEmail(string subject, string body)
{
SmtpClient smtp = null;
MailMessage message = null;
try
{
smtp = new SmtpClient
{
Host = "smtp.gmail.com",
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
Credentials = new NetworkCredential(sendAddress.Address, sendPassword),
Timeout = 20000
};
message = new MailMessage(sendAddress, toAddress)
{
Subject = subject,
Body = body
};
smtp.Send(message);
return "send mail ok";
}
catch (Exception e)
{
return "send mail fail";
}
finally
{
if (smtp != null) { smtp.Dispose(); }
if (message != null) { message.Dispose(); }
}
}
}
namespace WindowsFormsApp12
{
public partial class Form1 : Form
{
Mail mail = new Mail("email address type");
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string toAddress = this.textBox2.Text;
string subject = this.textBox1.Text;
string body = this.textBox3.Text;
if (toAddress == "")
{
MessageBox.Show("type in email address");
}
if (subject == "")
{
MessageBox.Show("type in email title");
}
if (body == "")
{
MessageBox.Show("type in email contents");
}
mail.SetToAddress(toAddress);
MessageBox.Show(mail.SendEmail(subject, body));
}
}
}
答案 0 :(得分:0)
您没有设置邮件的.from部分。
mail = new MailMessage(sendAddress, toAddress)
{
Subject = subject,
Body = body,
From = new MailAddress("Blah@Blah.com;")
};
可以添加到地址
mail.To.Add("email@address.com");
答案 1 :(得分:0)
MailAddress的构造函数的FormatException表示无效的电子邮件地址。来源MSDN documentation for MailAddress constructor。