i try to send an email with this code...but i have this error :"Client was not authenticated to send anonymous mail during MAIL FROM"
code:
var smtpClient = new SmtpClient()
{
Host = "smtp.office365.com",
Port = 25, //587
UseDefaultCredentials = false,
EnableSsl = true
};
smtpClient.UseDefaultCredentials = false;
smtpClient.DeliveryMethod= System.Net.Mail.SmtpDeliveryMethod.Network;
smtpClient.Credentials = new NetworkCredential("{mail}", "{password}","{domain}");
var message = new MailMessage
{
From = new MailAddress("{mail}","{display name}",System.Text.Encoding.UTF8),
Subject = "Test mail",
IsBodyHtml = false
};
message.To.Add("{mail}");
message.Body = "This is a test mail. ";
try{
smtpClient.Send(message);
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex);
}
thanks
This indicates that you are connecting to the SMTP client submission endpoint (smtp.office365.com), which can't be used for direct send. For direct send, use the MX endpoint for your Office 365 tenant, which ends with "mail.protection.outlook.com." So, please let your admin check the MX record. Moreover, please check if the SMTP port is 25/TLS.
Moreover, you can try the following suggestions to check if there is any improvement:
Remove the account and add it again to check the issue.
Try using another same tenant account to check the issue.
See Client was not authenticated to send anonymous mail for more information.
Related
I'm trying to send emails in .NET over SMTP. I linked serval custom aliases to the account in office365. (For example no-reply#domain-a.com, no-reply#domain-b.com)
But the mails arrive from No-Reply#mydomain.onmicrosoft.com. Even if I pass in a custom domain in the "from" parameter.
Here is my code:
var smtpClient = new SmtpClient(_settings.Endpoint, int.Parse(_settings.Port))
{
UseDefaultCredentials = false,
EnableSsl = true,
Credentials = new NetworkCredential(_settings.UserName, _settings.Password),
};
var mailMessage = new MailMessage
{
From = new MailAddress(message.From.Email, message.From.Name),
Subject = message.Subject,
Body = message.HtmlMessage,
IsBodyHtml = true
};
foreach (var addressee in message.Tos)
{
mailMessage.To.Add(addressee.Email);
}
try
{
smtpClient.Send(mailMessage);
}
catch (Exception e)
{
_logger.LogError(e, "Error sending email");
throw;
}
As username I'm using myaccount#mydomain.onmicrosoft.com. What am I missing here?
Nothing should be wrong with the office365/domain config cause it works when I'm trying to send the mail using powershell
$O365Cred = Get-Credential #the myaccount#mydomain.onmicrosoft.com credentials
$sendMailParams = #{
From = 'no-reply#mydomain-a.com'
To = 'me#gmail.com'
Subject = 'some subject'
Body = 'some body'
SMTPServer = 'smtp.office365.com'
Port = 587
UseSsl = $true
Credential = $O365Cred
}
Send-MailMessage #sendMailParams
Both Google (GMail) and Microsoft (Office365) replace the From header with the email address of the account used to send the mail in order to curtail spoofing.
If you do not want this, then you'll need to use another SMTP server or set up your own.
I found out that it works when sending the email to my personal Gmail. Meaning that there is nothing wrong with the code, but a configuration problem in my office365 / AD domain.
Apparently the outlook "address book" automatically fills in the "from / sender" part in the email, caused because I was sending an mail to the same domain as the one used for my SMTP account. (for example me#domain-a.com and noreply#domain-a.com).
I am trying to send mail through Gmail. I am sending mail successfully when I am testing on localhost, but this does not work when I upload it to a web host. I am seeing this type of error:
Request for the permission of type System.Net.Mail.SmtpPermission, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 failed.
Whenever I am using port 25 get this type of error below:
The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required
Below is my code of send email.
MailMessage mail = new MailMessage("host#gmail.com","User#gamil.com");
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.Subject = "Any String"
mail.Body = mailbody;
mail.IsBodyHtml = true;
SmtpServer.Port = 587;
SmtpServer.DeliveryMethod = SmtpDeliveryMethod.Network;
SmtpServer.UseDefaultCredentials = false;
SmtpServer.Credentials = new System.Net.NetworkCredential("xyz#gmail.com","123");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
Is there any solution? Please suggest to me!
Edit: OP Added extra information crucial to answering this question, but I'm keeping the old answer around as it might still help someone
New Answer:
This StackOverflow question already answered this question
OldAnswer:
As this StackOverflow answer already answered, you changed the Port on the SMTP Server to 587 instead of its default (25) and this requires elevated permissions causing this error change this:
SmtpServer.Port = 587;
to this:
SmtpServer.Port = 25;
and it should work
Note: When using SSL the port needs to be 443
Answer : Your code add SmtpDeliveryFormat.SevenBit
Example:
using (SmtpClient smtp = new SmtpClient())
{
NetworkCredential credential = new NetworkCredential
{
UserName = WebConfigurationManager.AppSettings["UserName"],
Password = WebConfigurationManager.AppSettings["Password"],
};
smtp.Credentials = credential;
smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtp.DeliveryFormat = SmtpDeliveryFormat.SevenBit;
smtp.Host = WebConfigurationManager.AppSettings["Host"];
smtp.Port = WebConfigurationManager.AppSettings["Port"].ToNcInt();
smtp.EnableSsl = Convert.ToBoolean(WebConfigurationManager.AppSettings["EnableSsl"]);
smtp.Send(mail);
}
Try This
using System;
using System.Net;
using System.Net.Mail;
namespace AmazonSESSample
{
class Program
{
static void Main(string[] args)
{
// Replace sender#example.com with your "From" address.
// This address must be verified with Amazon SES.
String FROM = "a#a.com";
String FROMNAME = "ABC";
// Replace recipient#example.com with a "To" address. If your account
// is still in the sandbox, this address must be verified.
String TO = "a#a.com";
// Replace smtp_username with your Amazon SES SMTP user name.
String SMTP_USERNAME = "a#a.com";
// Replace smtp_password with your Amazon SES SMTP user name.
String SMTP_PASSWORD = "ASJKAJSN";
// (Optional) the name of a configuration set to use for this message.
// If you comment out this line, you also need to remove or comment out
// the "X-SES-CONFIGURATION-SET" header below.
String CONFIGSET = "ConfigSet";
// If you're using Amazon SES in a region other than US West (Oregon),
// replace email-smtp.us-west-2.amazonaws.com with the Amazon SES SMTP
// endpoint in the appropriate AWS Region.
String HOST = "smtp-relay.sendinblue.com";
// The port you will connect to on the Amazon SES SMTP endpoint. We
// are choosing port 587 because we will use STARTTLS to encrypt
// the connection.
int PORT = 587;
// The subject line of the email
String SUBJECT =
"Amazon SES test (SMTP interface accessed using C#)";
// The body of the email
String BODY =
"<h1>Amazon SES Test</h1>" +
"<p>This email was sent through the " +
"<a href='https://aws.amazon.com/ses'>Amazon SES</a> SMTP interface " +
"using the .NET System.Net.Mail library.</p>";
// Create and build a new MailMessage object
MailMessage message = new MailMessage();
message.IsBodyHtml = true;
message.From = new MailAddress(FROM, FROMNAME);
message.To.Add(new MailAddress(TO));
message.Subject = SUBJECT;
message.Body = BODY;
// Comment or delete the next line if you are not using a configuration set
message.Headers.Add("X-SES-CONFIGURATION-SET", CONFIGSET);
using (var client = new System.Net.Mail.SmtpClient(HOST, PORT))
{
// Pass SMTP credentials
client.Credentials =
new NetworkCredential(SMTP_USERNAME, SMTP_PASSWORD);
// Enable SSL encryption
client.EnableSsl = true;
// Try to send the message. Show status in console.
try
{
Console.WriteLine("Attempting to send email...");
client.Send(message);
Console.WriteLine("Email sent!");
}
catch (Exception ex)
{
Console.WriteLine("The email was not sent.");
Console.WriteLine("Error message: " + ex.Message);
}
}
}
}
}
I published the site I completed using ASP.NET Web Forms but I'm having trouble sending mail. My web site does not send mail. There is no problem when I run in local.
My Fonksiyon.cs:
public static bool MailGonder(string gonderenaciklama, string kimemail, string kimeadi, string mailkonu, string mailicerik, string kimdenmail = "", bool IletisimFormuMu = false)
{
MailAddress From = new MailAddress(IletisimFormuMu ? kimdenmail : "My e-mail address is here", gonderenaciklama); // Gönderen kısmında görünen e-posta adresi.
MailAddress To = new MailAddress(kimemail, kimeadi); // Mailin gönderileceği adres.
MailMessage EMail = new MailMessage(From, To);
EMail.Subject = mailkonu;
EMail.Body = mailicerik;
EMail.IsBodyHtml = true;
EMail.BodyEncoding = Encoding.Unicode;
SmtpClient MailClient = new SmtpClient();
MailClient.Port = 587;
MailClient.Host = "smtp.gmail.com";
MailClient.EnableSsl = true; // Gmail üzerinden gönderme yapılacaksa veya sunucu kimlik doğrulaması gerektiriyorsa buraya true değerini vereceğiz.
MailClient.UseDefaultCredentials = true;
MailClient.Credentials = new System.Net.NetworkCredential("My e-mail address is here", "My password is here"); // Maili göndereceğimiz hesap bilgileri buraya giriyoruz. Mailimiz bu hesap üzerinden gönderilecek.
MailClient.DeliveryMethod = SmtpDeliveryMethod.Network;
try
{
MailClient.Send(EMail);
return true;
}
catch
{
return false;
}
}
My register.aspx button click:
string guid = Guid.NewGuid().ToString();
Fonksiyon.MailGonder("Ay Tasarım E-Posta Doğrulaması", TxtEPosta.Text, TxtAd.Text + " " + TxtSoyad.Text, "E-Posta Doğrulaması", "Lütfen aşağıdaki aktivasyon kodunu sitemizdeki ilgili alana yazarak üyeliğinizi aktif ediniz!<br />Aktivasyon Kodu: " + guid + "");
Nothing to do with your code, this is security feature of your gmail account.
these are the reasons that you can check
Google's security system has blocked the IP of your server
Google security system is actually pretty cool, if somebody gets his hands on your Gmail's password, well he won't be able to do much, unless he is using your IP address. Why? Because when Google spots an unusual IP address trying to connect to your account it will deny it access and will send you an email and eventually a text message on your mobile phone.
When you send a test email from MailPoet's Settings and you get the following message : " SMTP Error: Could not authenticate. | SMTP Error: Could not connect to SMTP host." then you might be entering this case scenario
The email you will receive to notify you of that unusual access will be as follow :
Allow new IP's in Google account
In your case when you setup your site to send with your Gmail account, you want to allow a new IP to use your Gmail's credentials. In order to allow a new unrecognized app simply go to https://security.google.com/settings/security/activity, find the line that concerns you and allow access.
Hope this helps to resolve your problem....
I'm trying to send email from asp.net mvc controller. Gmail account used here for smpt is configured to use with less security, so that's not the problem here.
but I don't get any error message neither any exception, but it not
deliver at my expected email address.
I'm using code
var text = "email body to deliver";
SendEmail("mydeliverEmailAddress#gmail.com", text);
public static bool SendEmail(string SentTo, string Text)
{
SmtpClient client = new SmtpClient();
client.Credentials = new NetworkCredential("myemail#gmail.com", "myGmailPass");
client.Port = 465;
client.Host = "smtp.gmail.com";
client.EnableSsl = true;
try
{
MailAddress
maFrom = new MailAddress("sender_email#domain.tld", "Sender's Name", Encoding.UTF8),
maTo = new MailAddress(SentTo, "Recipient's Name", Encoding.UTF8);
MailMessage mmsg = new MailMessage(maFrom.Address, maTo.Address);
mmsg.Body = "<html><body><h1>Some HTML Text for Test as BODY</h1></body></html>";
mmsg.IsBodyHtml = true;
mmsg.Subject = "Some Other Text as Subject";
mmsg.SubjectEncoding = Encoding.UTF8;
client.Send(mmsg);
}
catch (Exception ex)
{
}
return true;
}
Wait a minute. You are using your gmail account: myemail#gmail.com and trying to send an email on behalf of sender_email#domain.tld?
For more than obvious reasons that's never gonna work. So make sure that you are using the same email address as the one you are authenticating against:
maFrom = new MailAddress("myemail#gmail.com", "Sender's Name", Encoding.UTF8),
You can only send emails from the account you are authenticated against. Of course the recipient email can be any address that gmail can deliver to.
You've got another issue with your code. You are using a wring port here:
client.Port = 465;
The correct port that gmail SMTP works with is the following:
client.Port = 587;
Also you might want to ensure that you have enabled less secure apps in your gmail account or you will not be able to use SmtpClient in .NET to send emails using this SMTP: https://www.google.com/settings/security/lesssecureapps?pli=1
but I don't get any error message neither any exception, but it not
deliver at my expected email address.
What error message do you expect to get when you did the worst ever possible thing? You wrapped your code in a try/catch block and in your catch block you did absolutely nothing. You just consumed the exception:
catch (Exception ex)
{
}
So make sure that you do something useful with an exception if you are going to be catching it. For example something useful could be to log this exception and send an error message to the user saying that something bad happened and you couldn't send an email and that you are investigating the issue right now.
var smtpClient = new SmtpClient("YourSMTPServer", "SMTPServerPort"))
{
Credentials = new NetworkCredential("YourEmail",
"Password"),
EnableSsl = false
};
string fromEmail = "YourEmail";
var mailMessage = new MailMessage();
mailMessage.From = new MailAddress(fromEmail);
mailMessage.To.Add("Recipient's EMail");
mailMessage.Subject = "Test Mail";
mailMessage.Body = "This is test Mail";
mailMessage.IsBodyHtml = true;
smtpClient.Send(mailMessage);
I caught into big problem since am new to SMTP Email Server.
I have installed smtp server in my web server and configured the required details. My emails are now sending but in spam
I have implemented SendMail code using c# in my webapplication and I have one clarification on that.
string mailFrom = "Newsletter#my-domain.com";
string message = string.Empty;
System.Net.Mail.MailMessage email = new MailMessage(mailFrom, EmailAddress);
email.Subject = "Mail from my-domain.com";
email.Body = message;
email.IsBodyHtml = true;
email.Priority = MailPriority.High;
System.Net.Mail.SmtpClient mailClient = new SmtpClient();
System.Net.NetworkCredential basicAuthenticationInfo = new System.Net.NetworkCredential("username", "password");
mailClient.Host = "my-mail-server-domain.com";
mailClient.Port = 25;
mailClient.EnableSsl = false;
mailClient.UseDefaultCredentials = false;
mailClient.Credentials = basicAuthenticationInfo;
try
{
mailClient.Send(email);
}
catch (Exception ex)
{
log4net.ILog logger = log4net.LogManager.GetLogger("File");
logger.Error(ex.ToString());
}
What value should I give for mailFrom. Is valid email is required for From address? Does it cause sending mail as spam? I don't have emailid in the name of newsletter#my-domain.com. What shall I do for that?
Please anyone clarify on this.
It is the responsibility of the mail server the validation of the address, all could be good or bad for c#. I think your focus is wrong.
The from should be a valid email address. That is the email from where an email is sent. The network credentials that you specify must match with the from address. Once you provide a valid email address, the emails will not go to spam folder hopefully.