Sending email via Google - c#

i have this snippet code to send an email but every time i excute it ,i get this exception
The wait operation period expired
public static void CreateTimeoutTestMessage(string server)
{
string to = "touilhaythem1#gmail.com";
string from = "raddaouirami#gmail.com";
string subject = "Using the new SMTP client.";
string body = #"Using this new feature, you can send an e-mail message from an application very easily.";
MailMessage message = new MailMessage(from, to, subject, body);
SmtpClient client = new SmtpClient(server, 587);
client.EnableSsl = true;
client.Credentials=new NetworkCredential("raddaouirami#gmail.com", "XXXXXXXXX");
Console.WriteLine("Changing time out from {0} to 100.", client.Timeout);
client.Timeout = 100;
// Credentials are necessary if the server requires the client
// to authenticate before it will send e-mail on the client's behalf.
//client.Credentials = CredentialCache.DefaultNetworkCredentials;
try
{
client.Send(message);
}
catch (Exception ex)
{
Console.WriteLine("Exception caught in CreateTimeoutTestMessage(): {0}",
ex.ToString());
}
Console.ReadLine();
}

Of course you get a timeout - you specified 100ms for the timeout. That's pretty short. Contacting the server and sending the mail probably takes more than 100ms. Try something like 10000ms for ten seconds.
I know it's in the MSDN sample you copied and pasted from, but its way too short. It's best to remove the following lines:
Console.WriteLine("Changing time out from {0} to 100.", client.Timeout);
client.Timeout = 100;
Please try this (got the idea from here):
...
MailMessage message = new MailMessage(from, to, subject, body);
SmtpClient client = new SmtpClient(server, 587);
client.EnableSsl = true;
client.UseDefaultCredentials = false; // <--- NEW
client.Credentials = new NetworkCredential("raddaouirami#gmail.com", "XXXXXXXXX");
It might wait for authentication.

Where you have:
SmtpClient client = new SmtpClient(server, 587);
Break it up into:
SmtpClient client = new SmtpClient();
client.Host = "smtp.gmail.com";
client.Port = 587;
Because I don't see where you have defined server, and if you're trying to use gmail you can just declare it as the host like that to see if this gets you one step closer to your goal.
Also a side note, gmail smtp does not allow you to change the send from address, to prevent phishing, so if you did plan on allowing input to change the from variable it won't work, gmail defaults to the email provided in the credentials

Related

How to send mail without login with Gmail API?

Good work everyone,
Gmail API also requires user approval. But I have no idea how to use the token. I have to send a control mail to the user. Can I do without tokens?
I am making request with HttpClient. I am not using credentials.json.
As a postman, I can take and take tokens, but the token must not be renewed.
Sorry for my English. Thanks
I tried sending mail with Smtp Server. But it is blocked for security reasons. The only healthy solution is to send mail via Gmail API.
Using SMTP:
public class EmailService
{
public Task Execute(string UserEmail, string Body, string Subject)
{
//enable less secure apps in account google with link
//https://myaccount.google.com/lesssecureapps
try
{
SmtpClient client = new SmtpClient();
client.Port = 587;
client.Host = "smtp.gmail.com";
client.EnableSsl = true;
client.Timeout = 1000000;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential("***email here****", "****password here****");
MailMessage message = new MailMessage("***email here****", UserEmail, Subject, Body);
message.IsBodyHtml = true;
message.BodyEncoding = UTF8Encoding.UTF8;
message.DeliveryNotificationOptions = DeliveryNotificationOptions.OnSuccess;
client.Send(message);
return Task.CompletedTask;
}
catch (Exception e)
{
Console.Error.Write(e);
return Task.CompletedTask;
}
}
}
Also as mentioned in comment, enable less secure apps in google account.
https://myaccount.google.com/lesssecureapps
hint: less secure can't be enabled for emails with 2-step verification.

How do you schedule an email in C# using Gmail?

So, this is my email function, that sends an email using Gmail's SMTP:
public void Email(string subject, string body)
{
try
{
MailMessage message = new MailMessage();
SmtpClient smtp = new SmtpClient();
message.From = new MailAddress(email, emailname);
message.To.Add(new MailAddress(targetemail, targetname));
message.Subject = subject;
smtp.EnableSsl = true;
message.IsBodyHtml = true;
message.Attachments.Add(new Attachment(folder + #"\" + cbPrezentacja.SelectedItem.ToString() + "." + extension));
message.Body = body;
smtp.Port = 587;
smtp.Host = "smtp.gmail.com";
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential(email, password);
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.Send(message);
}
catch (Exception ex) {
MessageBox.Show(ex.ToString());
}
}
It works however, how would I schedule the email for a specific time? I don't mean making a Windows schedule/timer on the host (that requires leaving it on) or whatever, I want to do it via Gmail.
https://i.stack.imgur.com/eNG9D.png < This is how it works using Gmail. (sorry for the weird tint)
Is this even possible using System.Net.Mail or do I need a special Gmail API for that (if so, how?)? This is a private application for 1 computer, so it doesn't need to be super secure.
Thanks!
You can't.
There's nothing in SMTP to schedule it, when you do smtp.Send(message); the message is sent that exact moment.
Gmail has an API, but (as far I can see) it doesn't offer this functionality, so right now the only way to do it would be exactly what you say you don't want: your app should somehow wait till the desired time and send it.

the SMTP server response was 5.7.1 client was not authenticated

I have recently moved the web app from one server to another. No changes in the code or web config (apart from database connection) has been done.
In the old server, the application could send emails. In the new server, this error arises. Is there a configuration that I am missing here? I looked in IIS Manager, and the SMTP Email is not even activated in the old server. It seems to be an authentication issue, I do not know how the authentication works in this case.
I have not done the configuration in the old server so I do not know where to look.
public MailHelper(string sender, string recipient)
{
NetworkCredential cred = new NetworkCredential(SmtpUser, SmtpPassword);
message = new MailMessage(sender, recipient);
client = new SmtpClient();
client.Port = 25;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = true;
client.Host = SmtpHost;
}
public void Send(string subject, string body)
{
message.Subject = subject;
message.IsBodyHtml = true;
message.Body = body;
client.Send(message);
}
What are my next steps?
Cheers.
image of stacktrace: https://ibb.co/fd2jwPG

SmtpClient is unable to connect to Gmail using SSL

I see many posts on SMTPClient but I'm still stuck.
I am creating a C# Console application targeting the .NET 4.0 framework and running on a Windows 2008 R2 Datacenter (server).
I want send an email using SSL from a gmail account I just created.
If I use port 587, I get an exception:
The SMTP server requires a secure connection or the client was not authenticated
If I use port 465, I get another one:
Unable to read data from the transport connection: A blocking operation was interrupted by a call to WSACancelBlockingCall.
I realize this question has been asked several times in the past. All answers I see relate to the order in which UseDefaultCredentials is set. It must be set to false BEFORE the real credentials are set. I have followed this advice (as per the code below) and yet I still get a failure.
Other answers include switching ports from 465 to 587... which i have tried and just results in a different error (as stated above).
Here's my code:
NetworkCredential credentials = new NetworkCredential("something#gmail.com", "2-step-auth-Password");
MailAddress address = new MailAddress("something#gmail.com");
SmtpClient client = new SmtpClient("smtp.gmail.com", 465); // or 587
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.EnableSsl = true;
client.Credentials = credentials;
client.Timeout = 10000; // 10 seconds.
client.Host = "smtp.gmail.com";
//client.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);
MailMessage message = new MailMessage("example#gmail.com", recipients);
message.Subject = "Hello";
message.Body = "Goodbye";
message.BodyEncoding = Encoding.UTF8;
try
{
client.Send(message);
}
catch (Exception ex)
{
Console.WriteLine("Exception caught in CreateTestMessage2(): {0}", ex.ToString());
}
message.Dispose();
Update 2: I see another answer which may be my issue: gmail requires an application-specific password (which is apparently not available with my current gmail account. not sure why yet). but this may be my issue.
Update 3: I have followed all instructions. Generated 2-step authentication with Gmail, and still fails.
Below code works for me, you can try this:
SmtpClient smtp = new SmtpClient("smtp.office365.com");
//Your Port gets set to what you found in the "POP, IMAP, and SMTP access" section from Web Outlook
smtp.Port = 587;
//Set EnableSsl to true so you can connect via TLS
smtp.EnableSsl = true;
System.Net.NetworkCredential cred = new System.Net.NetworkCredential("Username", "Password");
smtp.Credentials = cred;
MailMessage mail = new MailMessage();
mail.From = new MailAddress("Sender Email Address", "Sender Name");
StringBuilder mailBody = new StringBuilder();
mail.To.Add("ToEmailAddress");
mail.Subject = "Subject";
mail.IsBodyHtml = true;
mail.Body = "Body Text";
try
{
smtp.Send(mail);
}
catch (Exception ex)
{
}

Error sending mail with SmtpClient

I've been struggeling a lot with this now.
I try to send mail with my mvc application using my google apps account. But I keep getting errors. It doesn't matter which settings I use. I tried using both port 465 and 587 with ssl and authentication turned on. With 465 I get Operation Timed Out and with 587 I get this message:
The SMTP server requires a secure connection or the client was not
authenticated. The server response was: 5.5.1 Authentication Required
I tried turning of the firewall with no luck. I have also tried to turn off 2-step authentication but I figured out that it wasn't even turned on.
I hope that you can help me
Regards
Here is the code as requested:
public static void SendMail(MailAddress from, MailAddress to, string subject, string body) {
MailMessage mail = new MailMessage();
mail.From = from;
mail.To.Add(to);
mail.Subject = subject;
mail.Body = body;
SmtpClient client;
if (Settings.Port != null)
client = new SmtpClient(Settings.Host, Int32.Parse(Settings.Port));
else
client = new SmtpClient(Settings.Host);
client.EnableSsl = Settings.UseSSL;
client.Timeout = 50000;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
if (Settings.UseAuthentication) {
client.Credentials = new NetworkCredential(Settings.Username, Settings.Password);
client.UseDefaultCredentials = false;
}
client.Send(mail);
}
I have checked all obvius stuff like username and password (username is formed like user#domain.com). I've also stepped through the code to verify my settings class is working as it should
I found out what the problem was. client.UseDefaultCredentials = false; must go before the credentials is set. Now client.Sendmethod returns without exceptions.

Categories