0

I am using following code to send email.when i am tring to send mail i am getting the error message

MailMessage mail = new MailMessage(from.txt, to.txt, subject, body);
SmtpClient clint = new SmtpClient();
//for determile email smtp...
string x = from.txt;
int startIndex = x.IndexOf('@');
int endIndex = x.LastIndexOf('.');
int length = endIndex - startIndex;
string xx = x.Substring(startIndex + 1, length - 1);

if (xx == "gmail" || xx == "Gmail")
{
    clint.Host = "smtp.gmail.com";
    clint.Port = 587;
    clint.EnableSsl = true;
}
if (xx == "Hotmail" || xx == "hotmail" || xx == "live" || xx == "Live")
{
    clint.Host = "smtp.live.com";
    clint.Port = 587;
    clint.EnableSsl = true;
}
if (xx == "yahoo" || xx == "Yahoo")
{
    clint.Host = "smtp.mail.yahoo.com";
    clint.Port = 465;
    clint.EnableSsl = true;
}
clint.Credentials = new System.Net.NetworkCredential(username, password);
clint.DeliveryMethod = SmtpDeliveryMethod.Network;
clint.UseDefaultCredentials = false;
clint.Send(mail);
MetroMessageBox.Show(this, "Email Successfully Send", "Success",
                    MessageBoxButtons.OK, MessageBoxIcon.Information);

and also how can attach any file to this email

vivek
  • 1,595
  • 2
  • 18
  • 35
Amjad
  • 330
  • 7
  • 22
  • username should be full email address. are you? – Balagurunathan Marimuthu Oct 08 '16 at 06:48
  • Enable two-factor authentication (aka two-step verification) , and then generate an application-specific password. Use that newly generated password to authenticate via SMTP. – Balagurunathan Marimuthu Oct 08 '16 at 06:50
  • Why don't you just use the SMTP server your service provider lets you use and make it easier? – Sami Kuhmonen Oct 08 '16 at 06:52
  • If you are testing this code with gmail, you will have to enable access to less secure apps in your google account from [here](https://myaccount.google.com/intro/security). Also set `clint.UseDefaultCredentials = false;` before `clint.Credentials = new System.Net.NetworkCredential(username, password);`. – Kamalesh Wankhede Oct 08 '16 at 09:14
  • Possible duplicate of [mail sending with network credential as true in windows form not working](http://stackoverflow.com/questions/32475832/mail-sending-with-network-credential-as-true-in-windows-form-not-working) – Salah Akbari Oct 08 '16 at 10:06

1 Answers1

0

For the error you got, I read online that you should use the UseDefaultCredentials before the Credentials line and that EnableSsl of your clint object should be set to true.

Reference here

and also how can attach any file to this email

You can by adding an attachment to the mail object :

mail.Attachments.Add(new Attachment(filename));

I forgot to mention that the double authentication in Gmail might be a problem. If so, refer to the second solution in the link I previously linked.

Community
  • 1
  • 1
Shak
  • 166
  • 7