2

I have an console app and I am trying to send mail from it.

My code.

    MailMessage message = new MailMessage(MailSender, "ToMe@me.com");

    message.Subject = "Using the new SMTP client.";
    message.Body = @"Using this new feature, you can send an e-mail message from an application very easily.";
    SmtpClient client = new SmtpClient();
    client.Port = 25;
    client.DeliveryMethod = SmtpDeliveryMethod.Network;
    client.UseDefaultCredentials = false;
    client.Host = "smtp.google.com";

    try
    {
        client.Send(message);
    }
    catch (Exception ex)
    {
        string t = ex.Message;
    }

Got this from here

I must be missing something since I am getting:

Failure sending mail.

What am I doing wrong here?

EDIT: inner Exeption.

InnerException = {"The remote name could not be resolved: 'smtp.google.com'"}

ThunD3eR
  • 3,216
  • 5
  • 50
  • 94
  • The exception contains more information than just the `.Message` property. Examine that information for details of why it failed. – David Mar 29 '16 at 12:35
  • what actual error are you getting? – BugFinder Mar 29 '16 at 12:35
  • Check if you are providing the username and password for your smtp server? – Rahul Tripathi Mar 29 '16 at 12:35
  • Well clearly thats why its not working then.. smtp.google.com is not resolving it doesnt know how to get to it – BugFinder Mar 29 '16 at 12:36
  • If you are trying to send via GMail there are many many examples, just google for *c# smtpclient gmail* - GMail requires an authenticated secure connection on a specific port. – Alex K. Mar 29 '16 at 12:36
  • Go to google website and find out parameter setting for using Net Library with email. You are using Port 25 which is non secure and I don't think google is support this port number. You probably need to use a Secure port number. The google website will give more information. – jdweng Mar 29 '16 at 12:40

4 Answers4

2

You can try to use

smtp.gmail.com

instead of

smtp.google.com

Also try to make sure that you are providing the correct credentials along with the correct port. A server parameter info:

enter image description here

Source

So you can try something like this

MailMessage message = new System.Net.Mail.MailMessage(); 
string fromEmail = "youremailaddress@xyz.com";
string password = "yourPassword";
string toEmail = "recipientemailaddress@abc.com";
message.From = new MailAddress(fromEmail);
message.To.Add(toEmail);
message.Subject = "Using the new SMTP client.";
message.Body = "Using this new feature, you can send an e-mail message from an application very easily.";
message.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;

using(SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 587))
{
    smtpClient.EnableSsl = true;
    smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
    smtpClient.UseDefaultCredentials = false;
    smtpClient.Credentials = new NetworkCredential(fromEmail, password);

    smtpClient.Send(message.From.ToString(), message.To.ToString(), message.Subject, message.Body);   
}
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
  • also I was pretty sure it would need username authentication so needs to be on another port.. and supply credentials. – BugFinder Mar 29 '16 at 12:38
  • Alright this seems the way I want to go. However I am doing this on a local app and im sitting over a secured company internet connection. I am assuiming that there are other credentials needed in this situation since i am getting this: "ex = {"The SMTP server requires a secure connection or the client was not authenticated."}" – ThunD3eR Mar 29 '16 at 13:01
  • @Ra3IDeN:- Indeed you need the credentials! :) – Rahul Tripathi Mar 29 '16 at 13:02
  • I have added my login credentials but it is not enough – ThunD3eR Mar 29 '16 at 13:03
  • @Ra3IDeN:- Can you ping to the smtp using the command prompt and see if you can access it? Something like `ping smtp.gmail.com` – Rahul Tripathi Mar 29 '16 at 13:05
  • I can, and i get a response – ThunD3eR Mar 29 '16 at 13:06
  • @Ra3IDeN:- See the resolution for your error in this **[thread](http://stackoverflow.com/questions/20906077/gmail-error-the-smtp-server-requires-a-secure-connection-or-the-client-was-not)** – Rahul Tripathi Mar 29 '16 at 13:08
  • @Ra3IDeN:- Also you can try to check using `smtpClient.UseDefaultCredentials = true;` – Rahul Tripathi Mar 29 '16 at 13:09
  • 1
    Above were good attempts but I have other things on the network that are blocking me. Need to wait for network Admin to give me access. in any case i will use this approach. Thank you – ThunD3eR Mar 29 '16 at 13:29
  • 1
    @Ra3IDeN you are limited to ~100 emails per day with Gmail (if not less). Try debugging that one when you or another developer forgets in a few months. Solution: PostMark. – Kind Contributor Mar 29 '16 at 13:40
1

@Ra3IDeN ...hey brother try this...

 SmtpClient smtpClient = new SmtpClient("mail.yourwebsitename.com", 25);

smtpClient.Credentials = new System.Net.NetworkCredential("demo@yourwebsitename.com.com", "yourIdPassword");
smtpClient.UseDefaultCredentials = true;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.EnableSsl = true;
MailMessage mail = new MailMessage();

//code for: From ,CC  & To
mail.From = new MailAddress("demo@yourwebsitename.com", "yourwebsite");
mail.To.Add(new MailAddress("demo@yourwebsitename.com"));
mail.CC.Add(new MailAddress("youremailid@gmail.com"));

 smtpClient.Send(mail);
Mridul Koul
  • 120
  • 11
1

If you're trying to send email from a console application (your higher-level problem), I recommend using PostMark. Why:

  • NuGet - You can get the PostMark NuGet package and send email with a nice API. Convenient and simple.
  • Not marked as SPAM - You can configure your "server" with verification (including spf and signing). So your email will more likely reach the destination in their inbox rather than their SPAM box.
  • Free - to a point. I think it's 1000 emails for free then $1 per 1000. So that's pretty good. Compare that to any other vanilla SMTP server for rent. PostMark is cheap
  • Consistent - From Workstation DEV to server LIVE, the PostMark API is consistently accessible. I cannot stress how good that is. Often a server host will offer SMTP server endpoint but it will only work from inside their network, meaning you have to configure another SMTP server when you're doing DEV work on your workstation (or it simply wont work).
  • Async Interface - I'm not sure if built-in smtp client in .Net is async...
  • Tracking - Hey look at that, they have a tracking feature built-in. That's snazzy.

Example code for sending (source):

var message = new PostmarkMessage()
{
    To = "recipient@example.com",
    From = "sender@example.com",
    TrackOpens = true,
    Subject = "A complex email",
    TextBody = "Plain Text Body",
    HtmlBody = "<html><body><img src=\"cid:embed_name.jpg\"/></body></html>",
    Tag = "business-message",
    Headers = new HeaderCollection{
        {"X-CUSTOM-HEADER", "Header content"}
    }
};

var imageContent = File.ReadAllBytes("test.jpg");
message.AddAttachment(imageContent, "test.jpg", "image/jpg", "cid:embed_name.jpg");

var client = new PostmarkClient("server token");
var sendResult = await client.SendMessageAsync(message);
Kind Contributor
  • 17,547
  • 6
  • 53
  • 70
0
 MailMessage msg = new MailMessage("YourEmail@gmail.com", "DestinationEmail@something.com");


        msg.Subject = message.Subject;

        msg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString("Message Content here as HTML", null, MediaTypeNames.Text.Html));

        SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", Convert.ToInt32( 587));
        System.Net.NetworkCredential credentials = new System.Net.NetworkCredential("YourEmail@gmail.com", "YourPassword");
        smtpClient.EnableSsl = true;
        System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate (object s,
                    System.Security.Cryptography.X509Certificates.X509Certificate certificate,
                    System.Security.Cryptography.X509Certificates.X509Chain chain,
                    System.Net.Security.SslPolicyErrors sslPolicyErrors)
        {
            return true;
        };


        smtpClient.Credentials = credentials;
smtpClient.Send(msg);
Ali Hajahmed
  • 184
  • 3