出了什么问题?
我正在尝试发送电子邮件,但我在问题的标题中收到错误。为什么不将对象转换为'System.Net.Mail.MailMessage'。
private object message;
protected void btnSend_Click(object sender, EventArgs e)
{
String TMess = txtMessageBody.Text;
String TEmail = txtEmail.Text;
String TSub = txtSubject.Text;
//this particular email server requires us to login so
//create a set of credentials with the relevent username and password
System.Net.NetworkCredential userpass = new System.Net.NetworkCredential();
userpass.UserName = "email";
userpass.Password = "password";
//ensure the smtp client has the newly created credentials
client.Credentials = userpass;
if (TSub == "")
{
System.Windows.Forms.MessageBox.Show("Error: Enter the message.");
}
else
{
//create a new email from REPLACE_WITH_USER@gmail.com to recipient@domain.com
MailMessage message = new MailMessage("helloworld@gmail.com", txtEmail.Text);
}
//set the subject of the message, and set the body using the text from a text box
message.Subject = txtSubject.Text;
message.Body = txtMessageBody.Text;
//send the message
client.Send(message);
//clear the message box
//the email has been sent - either by displaying a message (e.g. a literal) or by redirecting them to a 'Message sent' page
txtMessageBody.Text = "";
txtEmail.Text = "";
txtSubject.Text = "";
}
答案 0 :(得分:0)
var client = new SmtpClient();
var message = new MailMessage("helloworld@gmail.com", txtEmail.Text);
var subject = txtSubject.Text;
var body = txtMessageBody.Text;
message.Subject = subject;
mail.Body = body;
client.Send(message);
绝对最低限度应该可以正常工作。尝试一次添加一行其他代码,看看它在哪里断开。
答案 1 :(得分:0)
问题在于你的if else循环。如果它转到if语句(而不是else语句),则mailmessage对象不存在。不存在的东西无法解析。
you can do it like this
MailMessage message = new MailMessage("helloworld@gmail.com", txtEmail.Text
if (TSub == "")
{
System.Windows.Forms.MessageBox.Show("Error: Enter the message.");
return;
}