通过Gmail帐户发送电子邮件问题

时间:2011-02-14 11:56:14

标签: c# .net email

我正在尝试使用Gmail在C#中发送电子邮件。每当用户收到电子邮件时,我希望'from'标题有另一个我自己指定的电子邮件地址。谁能告诉我我该怎么做?

MailMessage mailMsg = new MailMessage();
SmtpClient client = new SmtpClient();

client.Port = 587;
client.Host = "smtp.gmail.com";
client.EnableSsl = true;
client.Credentials = new System.Net.NetworkCredential(username, password);
MailAddress mailAdd = new MailAddress("jack2@gmail.com");

mailMsg.Sender = new MailAddress(username);
mailMsg.From = mailAdd;
//mailMsg.Headers.Add("Sender",username);
mailMsg.Bcc.Add(builder.ToString());

mailMsg.Subject = txtSubject.Text;
mailMsg.Body = txtBody.Text;
mailMsg.IsBodyHtml = chkHtmlBody.Checked;
if (System.IO.File.Exists(txtAttechments.Text))
{
System.Net.Mail.Attachment attechment = new Attachment(txtAttechments.Text);
mailMsg.Attachments.Add(attechment);
}

client.Send(mailMsg);

在上面的代码中,'username'和'password'字段包含另一个电子邮件地址和密码。收到的电子邮件中包含“from”标题值

1 个答案:

答案 0 :(得分:0)

如果您提供的邮件不是Gmail,也不使用IMAP服务,请尝试此操作。

MailMessage mailMsg = new MailMessage();
SmtpClient client = new SmtpClient();

client.Port = 587;
client.Host = "mail.youdomain.com"; //////EDITED
client.EnableSsl = false; //////EDITED
client.Credentials = new System.Net.NetworkCredential(username, password);
MailAddress mailAdd = new MailAddress("jack2@gmail.com");

mailMsg.Sender = new MailAddress(username);
mailMsg.From = mailAdd;
//mailMsg.Headers.Add("Sender",username);
mailMsg.Bcc.Add(builder.ToString());

mailMsg.Subject = txtSubject.Text;
mailMsg.Body = txtBody.Text;
mailMsg.IsBodyHtml = chkHtmlBody.Checked;
if (System.IO.File.Exists(txtAttechments.Text))
{
System.Net.Mail.Attachment attechment = new Attachment(txtAttechments.Text);
mailMsg.Attachments.Add(attechment);
}

client.Send(mailMsg);