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

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.

Related

Gmail SMTP failure using c# SmtpClient

Our application has the possibility to send emails via SmtpClient. One of our customer is trying to do so by using his gmail account and it fails resulting in a timeout. However, from our testing lab it works just fine (with another gmail account).
In the trace i can see that the server is not answering with Certificate, Server Key Exchange, Server Hello Done. And im wondering what can be the cause for this?
I also noticed in the traces, the customer is using TLSv1 so I tried to replicate the error on a Windows7 system but still it works for me.
oSmtp = new SmtpClient(this.host, this.port);
oSmtp.DeliveryMethod = SmtpDeliveryMethod.Network;
oSmtp.EnableSsl = ssl;
NetworkCredential oCredential = new NetworkCredential(this.userName, this.password);
oSmtp.Credentials = oCredential;
oSmtp.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);
string userState = null;
oSmtp.SendAsync(oMsg, userState);
As far as the code goes, enableSsl is true, the port is 587 and we also instructed our customer to check his gmail account and allow less secure applications.
We will ask the customer for more specific details and try to put more traces in our application, but i would like to know if there is anything that can prevent the server to answer with Certificate,...
Inspecting the traces revealed no significant difference between customers Client Hello and our test Client Hello.
Thanks!
This is a working sample i used few days ago:
string fromAddress = "fromaddress#gmail.com";
var toAddress = new MailAddress("fake#email.com", "To person");
const string fromPassword = "pass";
const string subject = "test";
const string body = "Hey now!!";
using (MailMessage mail = new MailMessage())
{
mail.From = new MailAddress(fromAddress);
mail.To.Add(toAddress);
mail.Subject = subject;
mail.Body = body;
mail.IsBodyHtml = true;
//mail.Attachments.Add(new Attachment("C:\\file.zip"));
using (SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587))
{
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential(fromAddress, fromPassword);
smtp.EnableSsl = true;
smtp.Send(mail);
}
}
also make sure to enable Less secure app access for the gmail you are using to send data:

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)
{
}

An unhandled exception of type 'System.Net.Mail.SmtpException' occurred in System.dll

I'm trying out very simple tutorial on how to send e-mail via .NET and C#. However when I try to execute the code I got the following exception:
An unhandled exception of type 'System.Net.Mail.SmtpException' occurred in System.dll Additional information: The operation has timed
out.
So what I have done is to find the server settings to which I want to send mails to. This is very popular in my country:
Incoming settings
Protocol -> POP
Email address -> username#abv.bg
Username -> username#abv.bg
Password -> password
POP server -> pop3.abv.bg
Security type -> SSL
Server port -> 995
Outgoing server settings
Username -> username#abv.bg
Password -> password
SMTP server -> smtp.abv.bg
Security type -> SSL
Server port -> 465
then I created a Console project and in my main method I have this code:
SmtpClient client = new SmtpClient("smtp.abv.bg");
client.Port = 465;
client.EnableSsl = true;
client.Timeout = 100000;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential(
"username#abv.bg", "password");
MailMessage msg = new MailMessage();
msg.To.Add("username#abv.bg");
msg.From = new MailAddress("username#abv.bg");
msg.Subject = "Test subject";
msg.Body = "Test test test...";
client.Send(msg);
Since I have no experience with this I just try the code as you see it. No additional settings anywhere. The only thing that I think should not be problem but I think worth mentioning that here:
client.Credentials = new NetworkCredential(
"username#abv.bg", "password");
and here:
msg.To.Add("username#abv.bg");
I'm using the same e-mail. But I think this shouldn't be a problem. Any idea what am I doing wrong here?
Here is a working example (with Gmail) I wrote years ago for testing.
public void sendEmail(string body)
{
if (String.IsNullOrEmpty(email))
return;
try
{
MailMessage mail = new MailMessage();
mail.To.Add(email);
mail.To.Add("xxx#gmail.com");
mail.From = new MailAddress("yyy#gmail.com");
mail.Subject = "sub";
mail.Body = body;
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com"; //Or Your SMTP Server Address
smtp.Credentials = new System.Net.NetworkCredential
("yyy#gmail.com", "pw"); // ***use valid credentials***
smtp.Port = 587;
//Or your Smtp Email ID and Password
smtp.EnableSsl = true;
smtp.Send(mail);
}
catch (Exception ex)
{
print("Exception in sendEmail:" + ex.Message);
}
}
I would try this function with Gmail just to eliminate network related issues like firewall. When that will work, the rest is just to find the right settigs for the SMPT server

Sending email via Google

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

Relay access denied 5.7.1

I've got the error "Relay access denied", but I can connect my account with some email programs.
My code:
SmtpClient smtpClient = new SmtpClient();
NetworkCredential basicCredential =
new NetworkCredential("xx#xx.com", "xxx");
MailMessage message = new MailMessage();
MailAddress fromAddress = new MailAddress("xx#xx.com");
smtpClient.Host = "mail.xx.com";
smtpClient.Port = 587;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = basicCredential;
message.From = fromAddress;
message.Subject = subject;
message.IsBodyHtml = true;
message.Body = body;
message.To.Add("aa#aa.com");
try
{
smtpClient.Send(message);
}
catch (Exception ex)
{
//Relay access denied...
}
Does anyone know the reason for this?
Since your smtp host port is 587, I think you should set smtpClient.EnableSsl to true before calling its Send method.
Although this question is almost a year old now, I just stumbled upon the solution to a similar problem today. Apparently, the System.Net.Mail.SmtpClient class does not support the AUTH PLAIN method. Unfortunately, the SMTP server I was trying to use only offered AUTH PLAIN. Since the SmtpClient class and my server couldn't agree on an authentication method, the SmtpClient tried to send mails without authentication which got rejected by the SMTP server...
You should make sure that the SMTP server you are using offers at least one of the authentication mechanisms that SmtpClient supports. I couldn't find an exhaustive list of supported mechanisms but my server is now offering AUTH LOGIN which works with SmtpClient.
Please try
SmtpClient client = new SmtpClient("mail.xx#xx.com");
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential("xx#xx.com", "xxx");
client.Port = 587;
client.EnableSsl = true;
MailMessage maili = new MailMessage();
maili.Body = body;
maili.Subject = subject;
maili.IsBodyHtml = true;
maili.From = new MailAddress("xx#xx.com");
maili.To.Add("aa#aa.com");
try
{
ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };
client.Send(maili);
}
catch (Exception ex)
{
throw ex;
}
maili.Dispose();
In my case, the smtp password had changed, and gave me this error...
Usually it's very simple: the "From" e-mail address must have the same domain name as the domain name of the account from which the e-mail is being sent. So, if you send e-mail through a Hotmail account with the e-mail address e.g. "john.doe#hotmail.com", the "From" address must be set to the same.

Categories