Sending emails that requires a secure connection - c#

REMAKING QUESTION
This code doesn't work
The error is: The remote certificate is invalid according to the validation procedure.
var client = new SmtpClient("smtp.domain.com.br", 25000)
{
Credentials = new NetworkCredential("username", "password"),
EnableSsl = true
};
client.Send("emailfrom#domain.com.br", "emailto#gmail.com", "test", "testbody");
// I also tested like this
// client.Send("emailfrom#domain.com.br", "emailto#domain.com", "test", "testbody");
But this code works
var client = new SmtpClient("smtp.gmail.com", 587)
{
Credentials = new NetworkCredential("username", "password"),
EnableSsl = true
};
client.Send("emailfrom#domain.com.br", "emailto#gmail.com", "test", "testbody");
I tested the first code data in the Outlook, and works if I try to send to an email from the same domain.
I believe that the error is some SMTP configuration, but I don't know how to solve this. Any help?

which smtp server you using ?
if you are using gmail smtp server then you must use port number 587 that is required to send through gmail

based on the answer below you can pass in the values from the .config file but you will have to change what I have ..test this using hard coded values first if you like then convert the working version to use param values
using System.Net;
using System.Net.Mail;
var fromAddress = new MailAddress("from#gmail.com", "From Name");
var toAddress = new MailAddress("to#example.com", "To Name");
const string fromPassword = "fromPassword";
const string subject = "Subject";
const string body = "Body";
var _smtpClient = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials =
new NetworkCredential(fromAddress.Address, fromPassword)
};
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body
})
{
_smtpClient.Send(message);
}

did you try port 465. may be you can check this article.
http://support.google.com/mail/bin/answer.py?hl=en&answer=13287

I solve this using the digital certificate generated in the outlook and putting it on the server, where my application is running.
With the code in my question plus the certificate I finally made this works.
Here is a link on How to do this: create your own digital certificate

Related

How to send email using ASP.NET, C# and GMail

I have attempted to send an email using the GMail SMTP, and followed the guides on various other questions but I still cannot get emails to send from my GMail account.
This is the code I'm using:
protected void emailSend_Click(object sender, EventArgs e)
{
var fromAddress = new MailAddress(inputEmail.Text, inputName.Text);
var toAddress = new MailAddress("spikey666#live.co.uk", "Liane Stevenson");
const string fromPassword = "*********";
const string subject = "Web Dev Wolf Message";
var body = inputMessage.Text;
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
Credentials = new NetworkCredential("webdevelopwolf#gmail.com", fromPassword),
Timeout = 20000
};
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body
})
{
smtp.Send(message);
}
}
These are the things I've checked so far:
Turning on less secure apps on GMail
Checked the Gmail Username and Password are correct
Debugged and checked that all text fields have values and are loaded into variables
Check other port numbers suggested by Gmail help
Turned on POP/IMAP functionality on Gmail
Is there anything else I could be missing?
Before calling SmtpClient.Send(), add:
smtp.UseDefaultCredentials = false;
According to the MSDN SmtpClient page, UseDefaultCredentials is set to false by default, but there seems to be a bug somewhere that is setting it to true. Explicitly set it to false before sending the message and it should be all set.

sending email failed in .net when using google smtp server

I am trying to send email like this
var fromAddress = new MailAddress("fromaddress", "From Name");
var toAddress = new MailAddress("toaddress", "To Name");
const string fromPassword = "password";
const string subject = "Subject";
const string body = "Body";
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
};
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body
})
{
smtp.Send(message);
}
Console.WriteLine("Sent");
Console.ReadLine();
but it gives this error .
The SMTP server requires a secure connection or the client was not authenticated.
The server response was: 5.5.1 Authentication Required.
I am sing this code in simple console application on my local host . So whats the issue in my code ?
Update
I changed fromAddress email and it send email successfully . But i don't receive any email in my toAddress email's inbox/Spam .
Try to add DeliveryMethod = SmtpDeliveryMethod.Network when creating SmtpClient.
See post:
https://stackoverflow.com/a/489594/1432770
There is a variety of reasons for this discussed here:
Sending email through Gmail SMTP server with C#
Your code in the first link has worked for me.
Do you use two steps verification?
You need to sign in using application-specific passwords: https://support.google.com/accounts/answer/185833?hl=en
Your code worked for me too!

How to send email [duplicate]

This question already has answers here:
Sending email through Gmail SMTP server with C#
(31 answers)
Closed 9 years ago.
I am New in Asp.net, i need to send email from Asp.net using my Outlook.
I have one button in asp and when i click button(send) i want to send email.
I tried to use Hotmail and Gmail but remote server in blocked.
If you don't understand my question please tell me.
I tried this:
var smtpClient = new SmtpClient
{
Host = "outlook.mycompany.local",
UseDefaultCredentials = false,
Credentials = new NetworkCredential("myEmail#mycommpany.com", "myPassword")
};
var message = new System.Net.Mail.MailMessage
{
Subject = "Test Subject",
Body = "FOLLOW THE WHITE RABBIT",
IsBodyHtml = true,
From = new MailAddress("myemail#mycommapny.com")
};
// you can add multiple email addresses here
message.To.Add(new MailAddress("friendEmail#Company.com"));
// and here you're actually sending the message
smtpClient.Send(message);
}
Exeption Show: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.1 Client was not authenticated
Please how can i do that ?
Sending outbound email from an ASP.net web site can be problematic. Even if you get the SMTP information right, you still have to deal with:
Sender Policy Framework (SPF)
Whitelists/Blacklists
Validation
Bouncebacks
It's very difficult to do this yourself, which is why you might want to consider using a service provider instead. You simply use their API (often a REST call), and they do the rest. Here are three such providers:
SendGrid
Mandrill
Mailgun
Mandrill has a low-end free plan, and so does SendGrid if you are using it with Windows Azure. And they are all reasonably affordable, even for the larger plans.
I highly recommend using one of these with their own API instead of using System.Net.Mail yourself. But if you want, they also can act as an SMTP relay for you so you can use their SMTP servers and keep your System.Net.Mail code intact.
First of all get the company SMTP server settings (from your sys admins I guess), then you can do something like this:
// setting up the server
var smtpClient = new SmtpClient
{
Host = "your.company.smtp.server",
UseDefaultCredentials = false,
EnableSsl = true, // <-- see if you need this
Credentials = new NetworkCredential("account_to_use", "password")
};
var message = new MailMessage
{
Subject = "Test Subject",
Body = "FOLLOW THE WHITE RABBIT",
IsBodyHtml = true,
From = new MailAddress("from#company.com")
};
// you can add multiple email addresses here
message.To.Add(new MailAddress("neo#matrix.com"));
// and here you're actually sending the message
smtpClient.Send(message);
you can use this function. and one thing you have to store you email smtp login and password in web config file
/// <summary>
/// Send Email
/// </summary>
/// <param name="strFrom"></param>
/// <param name="strTo"></param>
/// <param name="strSubject"></param>
/// <param name="strBody"></param>
/// <param name="strAttachmentPath"></param>
/// <param name="IsBodyHTML"></param>
/// <returns></returns>
public Boolean sendemail(String strFrom, string strTo, string strSubject, string strBody, string strAttachmentPath, bool IsBodyHTML)
{
Array arrToArray;
char[] splitter = { ';' };
arrToArray = strTo.Split(splitter);
MailMessage mm = new MailMessage();
mm.From = new MailAddress(strFrom);
mm.Subject = strSubject;
mm.Body = strBody;
mm.IsBodyHtml = IsBodyHTML;
//mm.ReplyTo = new MailAddress("replyto#xyz.com");
foreach (string s in arrToArray)
{
mm.To.Add(new MailAddress(s));
}
if (strAttachmentPath != "")
{
try
{
//Add Attachment
Attachment attachFile = new Attachment(strAttachmentPath);
mm.Attachments.Add(attachFile);
}
catch { }
}
SmtpClient smtp = new SmtpClient();
try
{
smtp.Host = ConfigurationManager.AppSettings["MailServer"].ToString();
smtp.EnableSsl = true; //Depending on server SSL Settings true/false
System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
NetworkCred.UserName = ConfigurationManager.AppSettings["MailUserName"].ToString();
NetworkCred.Password = ConfigurationManager.AppSettings["MailPassword"].ToString();
smtp.UseDefaultCredentials = true;
smtp.Credentials = NetworkCred;
smtp.Port = 587;//Specify your port No;
smtp.Send(mm);
return true;
}
catch
{
mm.Dispose();
smtp = null;
return false;
}
}
Try Amazon Simple Email Service (http://aws.amazon.com/ses/). If you're new to Amazon Web Services (AWS) there might be a learning curve. However, once you're familiar with their SDK which can be found on Nuget (AWSSDK) the process is very straight-forward (Amazon does have a lot of little wrapper classes which can be quirky).
So, to answer the question "How to send email?", it looks something like:
var fromAddress = "from#youraddress.com";
var toAddresses = new Amazon.SimpleEmail.Model.Destination("someone#somedestination.com");
var subject = new Amazon.SimpleEmail.Model.Content("Message");
var body= new Body(new Amazon.SimpleEmail.Model.Content("Body"));
var message = new Message(subject , body);
var client = ConfigUtility.AmazonSimpleEmailServiceClient;
var request= new Amazon.SimpleEmail.Model.SendEmailRequest();
request.WithSource(fromAddress)
.WithDestination(toAddresses)
.WithMessage(message );
try
{
client.SendEmail(request);
}
catch (Amazon.SimpleEmail.AmazonSimpleEmailServiceException sesError)
{
throw new SupplyitException("There was a problem sending your email", sesError);
}
You can refer to below links:
http://www.codeproject.com/Tips/371417/Send-Mail-Contact-Form-using-ASP-NET-and-Csharp
send email asp.net c#
I hope it will help you. :)

Problem with app sending email followed by two empty emails

My app is sending 3 emails at the same time to the recipient, one being the correct email, and the other two contain the subject line, but an empty message. Could this code some how cause that? If not what do you suggest?
var fromAddress = new MailAddress(domainAddress, displayName);
var toAddress = new MailAddress(oInfo.SiteUser.email, oInfo.customerName);
var Bcc = new MailAddress("deleted");
var smtp = new SmtpClient
{
Host = SmtpHost(),
Port = SmtpPort(),
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(SmtpUsername(), SmtpPassword())
};
using (var msg = new MailMessage(fromAddress, toAddress)
{
IsBodyHtml = true,
Subject = "Confirmation for your recent order at " + displayName,
Body = body
})
{
msg.Bcc.Add(Bcc);
smtp.Send(msg);
}
No, that code won't send more than one mail.
Either you have some more code that is sending mail, or you are executing that code three times, but with different values for body.
The only problem I can see with that code is the line
var Bcc = new MailAddress("deleted");
but I assume you modified it for posting here?
I can't see an issue that would cause what you're seeing. I'd check the headers in the emails for clues. Also capturing network traffic on the machine sending the emails could help.

How do I tell my application to send an email?

How would I tell my application to send an email to a subscriber? How would I send it every week starting from the time the appication is launched.
Use the classes in the System.Net.Mail namespace to send emails from your app. Specifically, the MailMessage class serves this purpose.
To send emails periodically, you can use a timer (use System.Timers.Timer, for example) or you could use the built-in Windows task scheduler, which has rich functionality and runs as a service, so that you don't need to keep an interactive session open on your machine. I can give you a more detailed answer if you provide more details about the type of app you're developing.
I use this method to use gmail, and it works well for me.
var fromAddress = new MailAddress("From");
var toAddress = new MailAddress("To");
string fromPassword = textBox4.Text;
const string subject = "Test";
const string body = "Test Finished";
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new System.Net.NetworkCredential(fromAddress.Address, fromPassword)
};
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body
})
{
Attachment attachf = new Attachment("C:\\file.txt");
message.Attachments.Add(attachf);
smtp.Send(message);
}
}
I haven't created anything directly like this myself but I've seen solutions that use a Scheduled Task on the Server which are set to run on a certain date/time a small script that carries out what is required. This assumes you have your own server though...

Categories