0

I'm trying to send a email in C# using Gmail. I want the 'from' header to have another my own specified email address whenever user receive email. Could anyone please tell me how can I do this?

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);

In above code 'username' and 'password' fields contain another email address and password. The received email having 'from' header with value

Femaref
  • 60,705
  • 7
  • 138
  • 176
Avatar
  • 11
  • 2
  • Duplicate of http://stackoverflow.com/questions/3304699/how-to-set-from-address-to-any-email-other-gmail-in-sending-email-in-net-thro and http://stackoverflow.com/questions/3871577/change-sender-address-when-sending-mail-through-gmail-in-c. Basically, with Gmail, can't be done (by design) – Tom Juergens Feb 14 '11 at 12:02

1 Answers1

0

TRY this if your mail provide is not gmail and also not using IMAP services.

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);
Bhavik Goyal
  • 2,786
  • 6
  • 23
  • 42
  • He clearly states that he is using gmail so your solution won't work. He shoudl read this thread http://stackoverflow.com/questions/4677258/send-email-using-system-net-mail-through-gmail-c – Security Hound Feb 14 '11 at 17:20