Port for Sending Email for gmail account - c#

Please can some one help me out whether the correct port for sending email from an gmail account is 25 ,465 or 587. I checked on some forms it says that C# classes does not support sending email using SSL it uses TSL and the port used for TSL is 587. IS it correct? I am confused.

Gmail usually works with Port Number 587 in .net Application.
Check the following Example Code sample
System.Net.Mail.SmtpClient SmtpClientObject = new System.Net.Mail.SmtpClient();
SmtpClientObject.UseDefaultCredentials = false;
SmtpClientObject.Credentials = new System.Net.NetworkCredential("MyUserName#gmail.com", "myPassword");
SmtpClientObject.Host = "smtp.gmail.com";
SmtpClientObject.Port = 587;
SmtpClientObject.EnableSsl = true;
SmtpClientObject.Send("MyUserName#gmail.com", "YourUserName#gmail.com", "TestSubject", "MessageBody");

Related

C# Unable to send email from G Suite Company account

This is how I am sending email:
MailMessage m = new MailMessage();
m.From = new MailAddress("support#big-apps.org", "Big Apps.");
m.To.Add(new MailAddress("faizan003#gmail.com"));
m.Subject = "Test Subject";
m.Body = String.Format("This is Test email");
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Port = 465;
smtp.EnableSsl = true;
smtp.Credentials = new System.Net.NetworkCredential()
{
UserName = "support#big-apps.org",
Password = "mypassword"
};
smtp.EnableSsl = true;
smtp.Send(m);
Is there any setting that I need to enable in G Suite Admin?
I need to send email from support#big-apps.org
The port 465 is the issue. The SmtpClient EnableSsl option is actually using TLS. Gmail's TLS port is 587.
From Microsoft's Documentation:
https://learn.microsoft.com/en-us/dotnet/api/system.net.mail.smtpclient.enablessl?view=netframework-4.8
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.

Can't send email using implicit SSL smtp server

I wrote up a sample program by copying the code in this KB article with some little edit as far as user's info. It uses the deprecate .NET library System.Web.Mail to do it because the new System.Net.Mail does not support implicit SSL. I went and tested it with Google smtp server on port 465 which is their implicit email port and everything works. However, when I gave this to a client to test it at his network, nothing get sent/receive, here is the error:
2013-03-07 15:33:43 - The transport failed to connect to the server.
2013-03-07 15:33:43 - at System.Web.Mail.SmtpMail.LateBoundAccessHelper.CallMethod(Object obj, String methodName, Object[] args)
2013-03-07 15:33:43 - at System.Web.Mail.SmtpMail.CdoSysHelper.Send(MailMessage message)
2013-03-07 15:33:43 - at System.Web.Mail.SmtpMail.Send(MailMessage message)
I'm not very well versed when it comes to email SSL so here is my possible theory to the root cause:
Assume he is using the right smtp server and right port (SSL port), I wonder if if any of the following could be the cause:
They are using SSL on the mail server and yet he does not have the certificate installed on the machine where he runs my program from even though he is on the same domain and use the same email domain as a sender.
They are using SSL but they maybe using NTLM or Anonymous authentication while my program uses basic authentication.
Sorry if I provide little information because I myself is quite foreign in this area so I'm still researching more.
Do you know of any steps I can do at my end to ensure my little test program can send using the smtp server of an implicit SSL email server?
Edit: I did add the following line in my code to indicates I'm using SSL.
oMsg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl", "true");
Maybe this is to late to answer but have a look on https://sourceforge.net/p/netimplicitssl/wiki/Home/
You can send mail to port 465
Without the need of modifying your code, that much.
From the wiki page of project :
var mailMessage = new MimeMailMessage();
mailMessage.Subject = "test mail";
mailMessage.Body = "hi dude!";
mailMessage.Sender = new MimeMailAddress("you#gmail.com", "your name");
mailMessage.IsBodyHtml = true;
mailMessage.To.Add(new MimeMailAddress("yourfriend#gmail.com", "your friendd's name"));
mailMessage.Attachments.Add(new MimeAttachment("your file address"));
var emailer = new SmtpSocketClient();
emailer.Host = "your mail server address";
emailer.Port = 465;
emailer.EnableSsl = true;
emailer.User = "mail sever user name";
emailer.Password = "mail sever password" ;
emailer.AuthenticationMode = AuthenticationType.PlainText;
emailer.MailMessage = mailMessage;
emailer.OnMailSent += new SendCompletedEventHandler(OnMailSent);
//Send email
emailer.SendMessageAsync();
// A simple call back function:
private void OnMailSent(object sender, AsyncCompletedEventArgs asynccompletedeventargs)
{
Console.Out.WriteLine(asynccompletedeventargs.UserState.ToString());
}
Here I am using gmail smtp to send mail using c#. See the code below. It will give you an insight, How the stuffs are working. Replace gmail settings with your email server settings. Dont worry about the security certificates, they will be taken care of by the framework itself.
public static bool SendMail(string to, string subject, string body)
{
bool result;
try
{
var mailMessage = new MailMessage
{
From = new MailAddress("your email address")
};
mailMessage.To.Add(new MailAddress(to));
mailMessage.IsBodyHtml = true;
mailMessage.Subject = subject;
mailMessage.Body = body;
var userName = "your gmail username";
var password = "your gmail password here";
var smtpClient = new SmtpClient
{
Credentials = new NetworkCredential(userName, password),
Host = smtp.gmail.com,
Port = 587,
EnableSsl = true
};
smtpClient.Send(mailMessage);
result = true;
}
catch (Exception)
{
result = false;
}
return result;
}
The piece of code you were referencing was pretty old and obselete too. CDO was used in ASP apps to send mails. I think you havent scroll down to see
Article ID: 555287 - Last Review: April 7, 2005 - Revision: 1.0
APPLIES TO
Microsoft .NET Framework 1.1
You are refering a code that is pretty old... anyways follow the code shown up, everything will be FINE...
UPDATE
My bad, I have'nt read it carefully. But
I am leaving the above code as it is, as it might be a help for you
or any other guy, who need the mailing functionality via SSL over
gmail or any other server later.
. Then in such case you need some third party app.I found you a library See here

How to send a Secure e-mail using SMTP

I am currently using Google Apps to send SMTP e-mails. If my project deploys some of the information that i am going to be sending will be confidential and i would like to make sure the transmission is secure. Can anyone please let me know what i need to do to ensure that i send a safe e-mail using smtp through the google apps smtp server? smtp.google.com.
Any help greatly appreciated.
From what I have been told i need to force Https and have a SSL cert in order to do this. I don't know if this is true?
You Can Use 'smtp.EnableSsl = true' For Enable SSL for security.
MailMessage mail = new MailMessage();
mail.To.Add("" + to + "");
mail.From = new MailAddress("" + from + "");
mail.Subject = "Email using Gmail";
string Body = "Hi, this mail is to test sending mail" +
"";
mail.Body = Body;
mail.IsBodyHtml = true;
Attachment at = new Attachment(Server.MapPath("~/ExcelFile/TestCSV.csv"));
mail.Attachments.Add(at);
mail.Priority = MailPriority.High;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com"; //Or Your SMTP Server Address
smtp.Credentials = new System.Net.NetworkCredential(""+ username +"", ""+ password +"");
smtp.EnableSsl = true;
smtp.Port = 587;
smtp.Send(mail);
To enforce Network Security you have to use SSL. to enforce security of the data going from your webserver to mail server you need to send your mail over SSL. and to secure the HTTP request that triggers the mail action you need to enforce SSL over HTTP.
But the question is Security in what context ? If you need network security to ensure a 3rd party cannot eavesdrop or manipulate then SSL is your way to go.

Sending an email with the header return-path using windows virtual mail server

I'm trying to send an email message using the .NET MailMessage class which can also have the return-path header added so that any bounces come back to a different email address. Code is below:
MailMessage mm = new MailMessage(
new MailAddress(string.Format("{0}<{1}>", email.FromName, email.FromEmail)),
new MailAddress(emailTo));
mm.Subject = ReplaceValues(email.Subject, nameValues);
mm.ReplyTo = new MailAddress(string.Format("{0}<{1}>", email.FromName, email.FromEmail));
mm.Headers.Add("Return-Path", ReturnEmail);
// Set the email html and plain text
// Removed because it is unneccsary for this example
// Now setup the smtp server
SmtpClient smtp = new SmtpClient();
smtp.Host = SmtpServer;
smtp.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;
if (SmtpUsername.Length > 0)
{
System.Net.NetworkCredential theCredential =
new System.Net.NetworkCredential(SmtpUsername, SmtpPassword);
smtp.Credentials = theCredential;
}
smtp.Send(mm);
Whenever I check the email that was sent I check the header and it always seems to be missing return-path. Is there something I am missing to configure this correctly? As I said above I'm using the standard Virtual Mail Server on my development machine (XP) however it will run on Windows 2003 eventually.
Has anyone got any ideas why it isn't coming through?
The Return-Path is set based on the SMTP MAIL FROM Envelope. You can use the Sender property to do such a thing.
Another discussion on a related issue you will have sooner or later: How can you set the SMTP envelope MAIL FROM using System.Net.Mail?
And btw, if you use SmtpDeliveryMethod.PickupDirectoryFromIis, the Sender property is not used as a MAIL FROM; you have to use Network as a delivery method to keep this value.
I did not find any workaround for this issue.
PickupDirectoryFromIis, Sender property and SMTP MAIL FROM envelope

How to Send Email via Yandex SMTP (C# ASP.NET)

Formerly, I used my server as mail host and was sending emails via my own host. Now, I use Yandex as my mail server. I'm trying to send emails via Yandex SMTP. However, I could not achieve it. I get "the operation has timed out" message every time. I'm able to send & receive email with the same settings when I use Thunderbird. Hence, there is no issue with the account. I appreciate your guidance. You can see my code below:
EmailCredentials credentials = new EmailCredentials();
credentials.Domain = "domain.com";
credentials.SMTPUser = "email#domain.com";
credentials.SMTPPassword = "password";
int SmtpPort = 465;
string SmtpServer = "smtp.yandex.com";
System.Net.Mail.MailAddress sender = new System.Net.Mail.MailAddress(senderMail, senderName, System.Text.Encoding.UTF8);
System.Net.Mail.MailAddress recipient = new System.Net.Mail.MailAddress(recipientEmail, recipientName, System.Text.Encoding.UTF8);
System.Net.Mail.MailMessage email = new System.Net.Mail.MailMessage(sender, recipient);
email.BodyEncoding = System.Text.Encoding.UTF8;
email.SubjectEncoding = System.Text.Encoding.UTF8;
System.Net.Mail.AlternateView plainView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(System.Text.RegularExpressions.Regex.Replace(mailBody, #"<(.|\n)*?>", string.Empty), null, MediaTypeNames.Text.Plain);
System.Net.Mail.AlternateView htmlView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(mailBody, null, MediaTypeNames.Text.Html);
email.AlternateViews.Clear();
email.AlternateViews.Add(plainView);
email.AlternateViews.Add(htmlView);
email.Subject = mailTitle;
System.Net.Mail.SmtpClient SMTP = new System.Net.Mail.SmtpClient();
SMTP.Host = SmtpServer;
SMTP.Port = SmtpPort;
SMTP.EnableSsl = true;
SMTP.Credentials = new System.Net.NetworkCredential(credentials.SMTPUser, credentials.SMTPPassword);
SMTP.Send(email);
After so many trials & errors, I have found how to make it work. I have made the following changes on the code posted in the question:
Set SmtpPort = 587
Added the following 2 lines of code:
SMTP.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
SMTP.UseDefaultCredentials = false;
Additional note:
I use Azure server. I realized later that I did not configure the smtp endpoint for port 465. That being said, I had to add the 2 lines of code above in order to make email delivery work, just changing the port was not enough. My point is it is worth to check the defined ports on Azure and firewall before doing anything further.
I was able to make my code work by getting help from #Uwe and also #Dima-Babich, #Rail who posted on the following page Yandex smtp settings with ssl
. Hence, I think credits to answer this question should go to them.
Try using port 25 instead of 465 specified in Yandex help. I found this info on https://habrahabr.ru/post/237899/. They mentioned that it might be due to the fact that explicit SSL mode was implemented in the SmtpClient. Then port 25 is used for establishing connection in unencrypted mode and after that, protected mode is switched on.
I had the same problem.
I solved it by going to the Yandex mail, and then change some settings.
Go to:
1- Settings.
2- Email clients.
3- Set selected POP3 setting that is all.

Categories