Okay; I can't seem to send a mail message. I'm running this as a console application:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
namespace Email
{
class Program
{
static void EMail(string ToAddress, string Subject, string Body, string FromAddress, string Host, int Port, string Username, string Password)
{
System.Net.Mail.SmtpClient SMTPClient = new System.Net.Mail.SmtpClient(Host, Port);
System.Net.Mail.MailMessage Message = new System.Net.Mail.MailMessage();
Message.To.Add(new System.Net.Mail.MailAddress(ToAddress));
Message.From = new System.Net.Mail.MailAddress(FromAddress);
Message.Body = Body;
Message.Subject = Subject;
SMTPClient.EnableSsl = true;
SMTPClient.Credentials = new System.Net.NetworkCredential(Username, Password);
SMTPClient.Send(Message);
SMTPClient.SendCompleted += new System.Net.Mail.SendCompletedEventHandler(FinishedSending);
}
static void FinishedSending(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
{
Console.WriteLine("DONE!");
}
static void Main(string[] args)
{
EMail("***********", "Hi!", "This is a test, Sent from a C# application.", "******", "smtp.gmail.com", 465, "****************", "**************");
Console.ReadLine();
}
}
}
I'm not getting any errors, I'm not recieving it in my gmail account, And it's not writing "DONE!".
I have allowed port 465, outcoming and incoming. Telnetting smtp.gmail.com on port 465 results in a blank command prompt window.
Thanks.
Email should be going through if there is no exception.
It is not printing "DONE!" because you are hooking into the event after calling Send() method. Hook in the even before calling send.
Edit: And yes it should be SendAsync. Send is synchronous.
Also try these parameters in this order:
smtpClient.EnableSsl = true;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = (...)
This code works for me, in a new Winforms application:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
static void smtpClient_SendCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
{
var state = e.UserState;
//"Done"
}
private void Form1_Load(object sender, EventArgs e)
{
var smtpClient = new SmtpClient("smtp.gmail.com", 587)
{
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential("myEmail#gmail.com", "mypassword")
};
var message = new MailMessage("myEmail#gmail.com", "myEmail#gmail.com", "Subject", "body");
smtpClient.SendCompleted += new SendCompletedEventHandler(smtpClient_SendCompleted);
smtpClient.SendAsync(message, new object());
}
}
Go to Task -> Actions - > Edit Action and set "Start in (optional)" to folder where the executable file is.
I think that System.Net.Mail.SmtpClient::Send() may not be as synchronous as it should be. I was using this class in a powershell script that was to be run by the Task Scheduler. When running the script from a powershell console, I always received the message. However, when running the script as a scheduled task, I would not.
I resolved the problem by having the script sleep for 1 second after sending--I suspect the SMTP session was being killed by powershell shutting down at the end of the script, which doesn't happen when running it from an interactive session.
I know it's sloppy, but I haven't figured out a better way to make sure it's actually finished. Maybe there's a buffer that has to be flushed?
An alternative might be to call Send() with a bogus message after you send the actual message. I found that the message was consistently sent if I did this. This is still sloppy, but I find it a little bit less sloppy because it is more likely to actually require the buffers to be flushed before sending while waiting an arbitrary amount of time will definitely not cause it.
The reason it doesn't work is because you're targeting port 465. Using EnableSsl with port 25 (although not with Gmail) or port 587 should work for you.
SMTPS on port 465, or "Implicit SSL" as Microsoft calls it in a lot of places, is not supported by the SmtpClient class. The EnableSsl property controls whether or not the class will look for and use the STARTTLS command after an unencrypted connection has been established.
As per the Microsoft SmtpClient.EnableSsl Property documentation:
The SmtpClient class only supports the SMTP Service Extension for
Secure SMTP over Transport Layer Security as defined in RFC 3207. In
this mode, the SMTP session begins on an unencrypted channel, then a
STARTTLS command is issued by the client to the server to switch to
secure communication using SSL. See RFC 3207 published by the Internet
Engineering Task Force (IETF) for more information.
An alternate connection method is where an SSL session is established
up front before any protocol commands are sent. This connection method
is sometimes called SMTP/SSL, SMTP over SSL, or SMTPS and by default
uses port 465. This alternate connection method using SSL is not
currently supported.
If you really need to use SMTPS over port 465 there are solutions using the deprecated System.Web.Mail classes that use CDONTS behind the scenes, e.g. https://stackoverflow.com/a/1014876.
Related
I made a random Gmail account.I want that account to send to my personal Gmail account something, using C#. I found out about FluentEmail these days. This is the class:
public static class EmailSender
{
//the random account mail and password
private static string username = "blabla";
private static string password = "blabla";
static EmailSender()
{
NetworkCredential myCredentials = new NetworkCredential();
myCredentials.UserName = username;
myCredentials.Password = password;
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
DeliveryMethod = SmtpDeliveryMethod.Network,
Credentials = myCredentials,
Port = 465,
EnableSsl = true,
};
var sender = new SmtpSender(() => smtp);
Email.DefaultSender = sender;
}
public static async Task SendEmail(string body)
{
var email = await Email
.From(username)
.To("mymail")
.Subject("NEW BUG")
.Body(body)
.SendAsync();
if (email.Successful)
{
Acr.UserDialogs.UserDialogs.Instance.Alert("Your message was sent!", "Succesful", "Ok");
}
}
}
I don't know why but nothing happens when I click the send button.When I click it 2 times in a row the app crashes. I put a breakpoint at the start of the SendEmail function but I still don't know what's wrong. Maybe I set something wrong in the constructor?Thanks.
I'm not familiar with FluentEmail, but there are two points which are obviously problematic:
You check whether the mail has been sent successfully (if (email.Successful)). If it didn't, you just... do nothing. Instead, find out why the mail has not been sent and display that information instead. If your return object has a property Successful, I'm pretty sure it also has a property telling you what went wrong.
I did glimpse at the FluentEmail source code (based on your question), and it apparently uses .NET's built-in SmtpClient class. SmtpClient does not support SMTPS at port 465. The supported options are unauthenticated SMTP at port 25 or STARTTLS at port 587.
Below is the code I'm using. Please advise on how this can be rectified.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Net;
using System.Net.Mail;
public partial class mailtest : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void SendEmail(object sender, EventArgs e)
{
lblmsg.Text = "";
try
{
using (MailMessage mm = new MailMessage(txtEmail.Text, txtTo.Text))
{
mm.Subject = txtSubject.Text;
mm.Body = txtBody.Text;
//if (fuAttachment.HasFile)
//{
// string FileName = Path.GetFileName(fuAttachment.PostedFile.FileName);
// mm.Attachments.Add(new Attachment(fuAttachment.PostedFile.InputStream, FileName));
//}
mm.IsBodyHtml = false;
SmtpClient smtp = new SmtpClient();
smtp.Host = txtsmtphost.Text.Trim();
smtp.EnableSsl = false;
if (chkssl.Checked == true)
{
smtp.EnableSsl = true;
}
NetworkCredential NetworkCred = new NetworkCredential(txtEmail.Text, txtPassword.Text);
smtp.UseDefaultCredentials = true;
smtp.Credentials = NetworkCred;
smtp.Port = int.Parse(txtport.Text);
smtp.Send(mm);
lblmsg.ForeColor = System.Drawing.Color.DarkGreen;
lblmsg.Text = "Email sent successfuly !!";
//ClientScript.RegisterStartupScript(GetType(), "alert", "alert('Email sent successfuly !!');", true);
}
}
catch (Exception ex)
{
lblmsg.ForeColor = System.Drawing.Color.Red;
lblmsg.Text = "Failed " + ex.ToString();
ClientScript.RegisterStartupScript(GetType(), "alert", "alert('Failed');", true);
}
}}
The error message is:
System.Net.Mail.SmtpException: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.0 Authentication Required. Learn more at at System.Net.Mail.MailCommand.CheckResponse(SmtpStatusCode statusCode, String response) at System.Net.Mail.MailCommand.Send(SmtpConnection conn, Byte[] command, MailAddress from, Boolean allowUnicode) at System.Net.Mail.SmtpTransport.SendMail(MailAddress sender, MailAddressCollection recipients, String deliveryNotify, Boolean allowUnicode, SmtpFailedRecipientException& exception) at System.Net.Mail.SmtpClient.Send(MailMessage message)
Since this question keeps coming up as the first on Google, what today worked for me (11 June 2022) is what I will share. This question has been asked many times in similar way and many different things have worked for many people, but that stops now, there are no work around in "code" anymore (assuming your code is perfect but throwing exception as written in the title above)! Why because Google made a change (from https://support.google.com/accounts/answer/6010255):
Less secure apps & your Google Account:
To help keep your account secure, from May 30, 2022, Google no longer supports the use of third-party apps or devices which ask you to sign in to your Google Account using only your username and password.
Important: This deadline does not apply to Google Workspace or Google Cloud Identity customers. The enforcement date for these customers will be announced on the Workspace blog at a later date.
Now what do you do, its simpler then you think, go to https://myaccount.google.com/, Click "Security", enable Two-step Verification, once done, come back to the myaccount Security page, you will see "App passwords", open that, it will give you options for what you are trying to make a password for (a bunch of devices), select "Windows Computer", make a password, copy it, use this password in the NetworkCredential class object in your code, and your emails should start working again through Code.
This wasted so much of my hours yesterday, my Winforms app was working perfect till a couple days back it stopped sending emails.
The SMTP server requires a secure connection or the client was not authenticated.
To fix this error Go to your google account and generate an apps password
When running your code use the password generated instead of the actual users password.
This happens most often when the account has 2fa enabled.
Example with SmtpClient
using System;
using System.Net;
using System.Net.Mail;
namespace GmailSmtpConsoleApp
{
class Program
{
private const string To = "test#test.com";
private const string From = "test#test.com";
private const string GoogleAppPassword = "XXXXXXXX";
private const string Subject = "Test email";
private const string Body = "<h1>Hello</h1>";
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
var smtpClient = new SmtpClient("smtp.gmail.com")
{
Port = 587,
Credentials = new NetworkCredential(From , GoogleAppPassword),
EnableSsl = true,
};
var mailMessage = new MailMessage
{
From = new MailAddress(From),
Subject = Subject,
Body = Body,
IsBodyHtml = true,
};
mailMessage.To.Add(To);
smtpClient.Send(mailMessage);
}
}
}
You should enable the less secure app settings on the Gmail account you are using to send emails. You can use this Link to enable the settings.
More information about your problem here.
I am getting error "operation time out"and it throws me to the exception when i am sending email through my smtp server.I am using the code with gmail smtp and the same code works fine.In smtp details I am using network credential as my username and password i got when i created my email account on my domain and outgoing server and smtp port. following is my code..
protected void send_Click(object sender, EventArgs e)
{
string to = "xyz#gmail.com"; //To address
string from = "xyz#gmail.com"; //From address
MailMessage message = new MailMessage(from, to);
string mailbody = "Welcome to gmail...";
message.Subject = "Sending Email";
message.Body = mailbody;
message.IsBodyHtml = true;
SmtpClient client = new SmtpClient("server host",port);
System.Net.NetworkCredential basicCredential1 = new
System.Net.NetworkCredential("Username ","Password");
client.EnableSsl = true;
//client.Timeout = 10000;
client.UseDefaultCredentials =false;
client.Credentials = basicCredential1;
try
{
client.Send(message);
}
catch (Exception ex)
{
throw ex;
}
}
Because you haven't posted any log data, what you have already tried, and what didn't work, and only giving us the timeout as an outcome, there are a lot of open ended questions to your question. So instead of a specific answer, all I can do is give you vague directions what you need to do, to resolve your issue.
There can be a lot of issues with this sort of thing.
You write that this code performs correctly with another server, if I understand you correctly?
I would check:
A, Am I 100% sure my server connection string is correct? Also port wise?
B, Am I sure the ports are open for this communication to happen?(Check the firewalls are open)
C, Am I that there isn't some sort of version or configuration that is different between the gmail smtp, and you local smtp?
D, Check the SMTP server logs, if you are even receiving the request.
D1, if you are receiving, check which error is causing the timneout, this will likely be in the log.
D2, Start from A, There is something wrong with your connection to the SMTP server.
This is my first post on Stack, and I've literally just started programming, so please, be patient.
I'm attempting to send an email to "x" email address when Button 1 is pressed. I've looked around, and every thread is jargon-heavy and not in my context. Please pardon me if this is a "newb' question, or if it's already thouroughly answered somewhere else.
The error I'm getting is "
Failure sending mail. ---> System.IO.IOException: Unable to read data from the transport connection: net_io_connectionclosed."
Here's my code
using (SmtpClient smtp = new SmtpClient())
{
smtp.Host = "smtp.gmail.com";
smtp.Port = 465;
smtp.Credentials = new NetworkCredential("myemail", "mypassword");
string to = "toemail";
string from = "myemail";
MailMessage mail = new MailMessage(from, to);
mail.Subject = "test test 123";
mail.Body = "test test 123";
try
{
smtp.Send(mail);
}
catch (Exception ex)
{
Console.WriteLine("Exception caught in CreateTestMessage2(): {0}",
ex.ToString());
}
Any help is greatly appreciated!
The error you're getting could come from a plethora of things from a failed connection, to the server rejecting your attempts, to the port being blocked.
I am by no means an expert on SMTP and its workings, however, it would appear you are missing setting some of the properties of the SmtpClient.
I also found that using port 465 is a bit antiquated, and when I ran the code using port 587, it executed without an issue. Try changing your code to something similar to this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Mail;
using System.Net;
namespace EmailTest
{
class Program
{
static void Main(string[] args)
{
SendMail();
}
public static void SendMail()
{
MailAddress ma_from = new MailAddress("senderEmail#email", "Name");
MailAddress ma_to = new MailAddress("targetEmail#email", "Name");
string s_password = "accountPassword";
string s_subject = "Test";
string s_body = "This is a Test";
SmtpClient smtp = new SmtpClient
{
Host = "smtp.gmail.com",
//change the port to prt 587. This seems to be the standard for Google smtp transmissions.
Port = 587,
//enable SSL to be true, otherwise it will get kicked back by the Google server.
EnableSsl = true,
//The following properties need set as well
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(ma_from.Address, s_password)
};
using (MailMessage mail = new MailMessage(ma_from, ma_to)
{
Subject = s_subject,
Body = s_body
})
try
{
Console.WriteLine("Sending Mail");
smtp.Send(mail);
Console.WriteLine("Mail Sent");
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine("Exception caught in CreateTestMessage2(): {0}",
ex.ToString());
Console.ReadLine();
}
}
}
}
Tested to work as well. Also of note: if your Gmail account does not allow "Less Secure" apps to access it, you'll get an error and message sent to your inbox stating an unauthorized access attempt was caught.
To change those settings, go here.
Hope this helps, let me know how it works out.
i use the following code to send email :
public static bool SendEmail(string To, string ToName, string From, string FromName, string Subject, string Body, bool IsBodyHTML)
{
try
{
MailAddress FromAddr = new MailAddress(From, FromName, System.Text.Encoding.UTF8);
MailAddress ToAddr = new MailAddress(To, ToName, System.Text.Encoding.UTF8);
var smtp = new SmtpClient
{
Host = "smtp.datagts.net",
Port = 587,
EnableSsl = false,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = true,
Credentials = new System.Net.NetworkCredential("MeEmail#...", "Password")
};
using (MailMessage message = new MailMessage(FromAddr, ToAddr)
{
Subject = Subject,
Body = Body,
IsBodyHtml = IsBodyHTML,
BodyEncoding = System.Text.Encoding.UTF8,
})
{
smtp.Send(message);
}
return true;
}
catch
{
return false;
}
}
It works on local and when i use my web site under my local IIS but when i upload it to my website it does not work and does not send email even any error occurs.
is there anybody out there to help me about this ?
UPDATE1 : i remove the try catch and catch an error with this message : Failure sending mail
UPDATE2 : I change my stmp server and use my Gmail account , look at this code :
public static bool SendEmail(string To, string ToName, string From, string FromName, string Subject, string Body, bool IsBodyHTML)
{
try
{
MailAddress FromAddr = new MailAddress(From, FromName, System.Text.Encoding.UTF8);
MailAddress ToAddr = new MailAddress(To, ToName, System.Text.Encoding.UTF8);
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new System.Net.NetworkCredential("MeEmail#gmail.com", "Password")
};
using (MailMessage message = new MailMessage(FromAddr, ToAddr)
{
Subject = Subject,
Body = Body,
IsBodyHtml = IsBodyHTML,
BodyEncoding = System.Text.Encoding.UTF8,
})
{
smtp.Send(message);
}
return true;
}
catch
{
return false;
}
}
and now i get an error yet :(
I get the "MustIssueStartTlsFirst" error that mentioned in this link.
I am now trying to check #EdFS point and use port 25
UPDATE3: It is because i use the shared server , i just can change the port to 25 , and steel it does not work an give the same error, I am trying to get support from my server backup team
Assuming the SMTP server (smtp.datagts.net) is running fine, some items to check:
Your code seems to be using UseDefaultCredentials=true, but on the next line your are providing credentials
As mentioned in the comments check that Port 587 isn't blocked at your web host
If you are hosted on a shared server (not a dedicated machine), it's likely ASP.Net is set for medium trust. IF so, you cannot use any port for SMTP other than Port 25.
Update:
To try and get to the error. In your LOCAL (development) machine, add this to your web.config:
<system.web>
...
<securityPolicy>
<trustLevel name="Medium" />
</securityPolicy>
...
ASP.Net on your local machine runs in FULL TRUST. The above setting makes the current web site/application you are working on run in medium trust. You can remove/comment as necessary. The point of this exercise is to try and match what your web host settings are (it's obviously different if things work in your local machine then dies when published). It would be nice to just obtain the info from your web host..but until then....
Then try both Port 587 and 25.
It should fail on port 587 with a security exception (because of medium trust)
If your mail server only accepts SMTP connections on port 587, then of course, port 25 will not work either (but you should get a different error). The point being "...it still doesn't work..." in this case is that the SMTP server (smtp.datagts.net) only accepts connections on port 587
GMAIL is the same story. You cannot use Port 587 if your web host settings for ASP.Net is medium trust. I have been through this many times - it will "work" in my local machine, but as soon as I enable medium trust in my local development machine, it will fail.
You should ask your web host what their settings are for ASP.Net - if its some "custom" setting you can ask for a copy and use that in your dev box as well.