Sending email using smtp works only after sending it by outlook - asp.net-mvc

I'm trying to send email using asp.net mvc application. Smtp client is configured in web.config e.g.:
<mailSettings>
<smtp from="noreply#test.sk">
<network host="mail.test.sk" defaultCredentials="false" userName="noreply#test.sk" password="pass" port="25"/>
</smtp>
</mailSettings>
C#:
using (SmtpClient client = new SmtpClient())
{
MailMessage message = new MailMessage(from, to, subject, body);
client.Timeout = 10000;
client.Send(message);
return false;
}
The thing is, it doesn't work (I get timeout exception) until I try to send email using outlook. Right after sending email by outlook it successfully sends it also by my web application. Is there some special kind of authentication which outlook is doing which then allows all emails from my IP to be authenticated?? What is the reason it works only after sending it by outlook?
BTW:
I'm running the application in VS asp.net development server. When I deploy it to webhosting server, it doesn't work (timeout).
My webhosting provider told me there is a classic smtp authentication on that server (not pop3 before smtp).
EDITED:
I figured out, when it worked and I tried it by telnet or traced it by wireshark, the communication started by:
220 mail2.hostmaster.sk ESMTP Postfix
EHLO fernet-PC
250-mail2.hostmaster.sk
250-PIPELINING
250-SIZE 104857600
250-ETRN
250-STARTTLS
250-AUTH PLAIN LOGIN
250-AUTH=PLAIN LOGIN
250-ENHANCEDSTATUSCODES
250-8BITMIME
250 DSN
...
Compared to when it didn't work (just tried a day before), the whole communication looked like:
220-mail2.hostmaster.sk ESMTP Postfix
EHLO fernet-PC
250-mail2.hostmaster.sk
250-SIZE 104857600
250-ETRN
250-STARTTLS
250-ENHANCEDSTATUSCODES
250-8BITMIME
250 DSN
So there is a difference in supported auth methods and support for pipelining. I guess that System.Net.Mail.SmtpClient then doesn't know which authentication method should it use and so it stucks and therefore I'm getting the timeout exception.
That's interesting that outlook has no problems to connect and send email.
I solved my problem by not using their smtp server, as I'm running out of time. I'm using gmail's smtp server instead. I created new gmail account where I set alias to what I needed, so the email looks like it didn't come from gmail on the first look.

I have fixed a similar problem on a site and came across this Question while researching the issue.
The code below works for Google Apps for Business;
public class SendSMTPEmail
{
public static void SendText(string ToName, string ToEmail, string FromName, string FromEmail, string Subject, string Content)
{
MailAddress from = new MailAddress(ToEmail, ToName);
MailAddress to = new MailAddress(ToEmail, ToName);
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
Credentials = new NetworkCredential("username#googlemail.com", "yourpassword"),
Timeout = 20000
};
MailMessage message = new MailMessage()
{
From = from,
Body = Content,
Subject = Subject
};
message.To.Add(to);
smtp.Send(message);
}
}
Does this help?

Related

Unable to send emails from Godaddy Plesk Hosting for ASP .NET project

I am having a hard time wrapping my head around this issue. I followed this link- https://ca.godaddy.com/help/send-email-using-systemnetmail-in-windows-hosting-19291. Basically, they want us to use their network host it seems.
Can someone help me figure out what I need to fix this?
This is the code I am using in web.config-
<mailSettings>
<smtp from="tefgh#gmail.com">
<network host="relay-hosting.secureserver.net" port="25" />
</smtp>
</mailSettings>
In controller-
MailMessage mail = new MailMessage();
mail.From = new MailAddress("tefgh#gmail.com");
mail.To.Add("abcd#gmail.com");
mail.Subject = "Hello";
mail.Body = "body";
SmtpClient smtp = new SmtpClient();
smtp.UseDefaultCredentials = false;
smtp.Send(mail);
I want to receive the email successfully. It does not even throw any errors. When I use real Gmail SMTP settings, then it throws error

Is it possible to use OAuth 2.0 for Office365 SMTP?

I have an email application for sending emails that was written in house. We have set it with the option to use OAuth 2.0 with GMail (personal and business accounts) and Outlook.com accounts without issues.
We can also authentication with user ids and passwords but we prefer OAuth 2.0 as we don't save passwords anywhere that way.
We now have requests to do this for Office365 accounts.
I notice that the hello message on the Office365 smtp server (smtp.office365.com port 587) does not offer the XOAUTH2 option.
250-BY2PR0601CA0005.outlook.office365.com Hello [xx.xx.xx.xx]
250-SIZE 157286400
250-PIPELINING
250-DSN
250-ENHANCEDSTATUSCODES
250-AUTH LOGIN
250-8BITMIME
250-BINARYMIME
250 CHUNKING
But, the SMTP server for outlook.com does:
250-BLU436-SMTP14.smtp.hotmail.com Hello [xx.xx.xx.xx]
250-TURN
250-SIZE 41943040
250-ETRN
250-PIPELINING
250-DSN
250-ENHANCEDSTATUSCODES
250-8bitmime
250-BINARYMIME
250-CHUNKING
250-VRFY
250-AUTH LOGIN PLAIN XOAUTH2
250 OK
Is this possible to do with Office365? If not, can we point Office365 users to the outlook.com smtp server (smtp-mail.outlook.com) or are they totally different?
We'd rather not use the APIs just for sending emails if possible as the RESTful APIs for each provider will of course be quite different.
The reason for using OAuth 2.0 when sending email with an Office365 account is that we don't want to have to store passwords on our server. Also, if the user changes their password, we won't know unless they tell us or manually update it on our system side.
Using OAuth 2.0 this would solve this problem and allow the application to flow like with other email providers.
I really wanted this feature too. It would make Office365 apps that need to send mail that much easier!
I did some hunting, and found this which appears to be as close to an official answer as we are going to get (and the answer is a flat no).
Not sure if I'm missing something, but isn't this what you want? Looks like this was posted back in February. Interestingly, this article says that Oauth is supported for M365, but NOT for outlook.com users.
https://learn.microsoft.com/en-us/exchange/client-developer/legacy-protocols/how-to-authenticate-an-imap-pop-smtp-application-by-using-oauth
I made one example using javax.Mail and OAuth for desktop application. It opens logon screen to get acccessToken. I followed multiple instructions so probably there are too many permissions and props in JavaMail but I succeeded to send mail.
My example program (Github)
PHP Example with OAuth2.
[On GitHub] (https://github.com/larsonnn/php_smtp_xoauth2_microsoft.php)
<?php
/* composer.json
"require": {
"phpmailer/phpmailer": "^6.6",
"league/oauth2-client": "^2.6",
"thenetworg/oauth2-azure": "^2.1"
}
*/
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\OAuth;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\PHPMailer;
use TheNetworg\OAuth2\Client\Provider\Azure;
require "vendor/autoload.php";
$mail = new PHPMailer(true);
$provider = new Azure([
'clientId' => '',
'clientSecret' => '',
"scopes" => ["https://outlook.office.com/SMTP.Send"],
"tenant" => "",
"defaultEndPointVersion" => Azure::ENDPOINT_VERSION_2_0,
]);
$mail->setOAuth(
new OAuth(
[
'provider' => $provider,
'clientId' => '',
'clientSecret' => '',
'refreshToken' => '',
'userName' => 'mymail#office_365_email.tld',
]
)
);
//Server settings
$mail->SMTPDebug = SMTP::DEBUG_SERVER;
$mail->isSMTP();
$mail->Host = 'smtp.office365.com';
$mail->Port = 587;
$mail->SMTPAuth = true;
$mail->AuthType = 'XOAUTH2';
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$mail->CharSet = PHPMailer::CHARSET_UTF8;
//Recipients
$mail->setFrom('mymail#office_365_email.tld', 'name');
$mail->addAddress('spam#example.tld', 'Spam');
//Content
$mail->Subject = 'Here is the subject';
$mail->Body = 'Hallo';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
$mail->send();

MVC Application cannot send mail through local HMailServer

I am building a form in C#, .NET, and MVC. On the back end the form will send its contents over email. For testing, I am using a local install of hMailServer.
Initially I set HMS to run as localhost.localdomain; the SMTP setting for "local host name" is localhost. I attempted to connect to it on port 587, like so:
SmtpClient smtp = new SmtpClient
{
Host = WebConfigurationManager.AppSettings["emailServer"],
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = true,
Credentials = networkCredential
};
I have double- and triple-checked that the credentials are the mail server user and password that I set. Here they are, in case this helps:
<add key="emailUser" value="user#localhost.localdomain"/>
<add key="emailPassword" value="~~~"/>
<add key="emailServer" value="localhost.localdomain"/>
When using localhost.localdomain, sending mail throws an exception, with the outer message: "Failure sending mail", and the inner message: "The remote name could not be resolved: 'localhost.localdomain'."
So I tried using companyname.com. Sending mail throws an exception, with the outer message: "Failure sending mail", and the inner message: "Unable to connect to the remote server."
I expect either my HMS domain config is wrong or my protocol config is wrong. The HMS documentation didn't help me, but I may not have known what to look for.
ETA
hMail server status shows zero processed messages in a week, despite all my testing.
Here is how I configured it for development:
Created host file entry like following:
local.myname.com 127.0.0.1
Once done, I opened command prompt and make sure it is updated. I tested it by following:
tracert local.myname.com
It should return 127.0.0.1 if host file entry is updated.
Next, in hmail, we need to create a new domain: local.myname.com and add an email address with password. so your email address would be something like admin#local.myname.com.
Next is, in advance you need to double check the protocols configuration and IP range vs authentication configuration as well.
In my case I configured to block external incoming and outgoing emails and skipped authentication for internal emails. So basically that;s what you can do in advance - IP range configuration. Then with the development, you just need to make sure all your emails are *#local.myname.com and it should work.
Also enable logging in hmail to get detailed error that can help solve the problem because hmail's help documentation works directly with their error codes nicely.
hMail is actually good choice for real emails. For development, I would recommend using smtp4dev though.

mail server requires authentication when attempting to send to a non-local e-mail address when using MVCMailer

I want to send NewsLetter Emails to users.
I have done like this:
public ActionResult SendNewsLetter()
{
_userMailer.NewsLetter().Send();
return View();
}
and in userMailer class:
public virtual MvcMailMessage NewsLetter(string userEmail)
{
//ViewBag.Data = someObject;
return Populate(x =>
{
x.Subject = "NewsLetter";
x.ViewName = "NewsLetter";
x.To.Add("hello#mydomain.mobi");
x.Bcc.Add(userEmail);
});
}
I add submitted newsletter emails to bcc.
but when I send it I encounter this issue:
Bad sequence of commands. The server response was: This mail server
requires authentication when attempting to send to a non-local e-mail
address. Please check your mail client settings or contact your
administrator to verify that the domain or address is defined for this
server.
if remove bbc I can send email normaly because I have provided authentications for hello#mydomain.mobi in web.config.
<system.net>
<mailSettings>
<!-- Method#1: Configure smtp server credentials --><smtp deliveryMethod="Network" from="hello#mydomain.com">
<network host="mydomain.com" port="25" userName="hello#mydomain.com" password="123456" enableSsl="false" />
</smtp>
</mailSettings>
but Im amazed why I cannot send email to other emails?
does somebody have any idea?
The error message that you're encountering isn't related to MVCMailer at all. I'd contact the system administrator of the SMTP server you're attempting to use and see if you're allowed to use the hello#mydomain.com user that you're authenticating with to send email to the value of userEmail. A lot of SMTP servers that web servers use will often have limits or restrictions on email to prevent spamming.

Don't send mails asp .net application hosted only work in localhost

I have a problem when I upload an application to the Web. I want to send a mail to several users but it doesn't work, but when I send in localhost work properly.
Here's my code to send the mail
System.Net.Mail.MailMessage correo = new System.Net.Mail.MailMessage();
correo.To.Add(mail_usuario);
correo.Body = cuerpomensaje;
correo.BodyEncoding = System.Text.Encoding.UTF8;
correo.Priority = System.Net.Mail.MailPriority.Normal;
correo.IsBodyHtml = true;//false tested too.
System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient();
smtp.Host = "mail.cscdecision.com";
smtp.Credentials = new System.Net.NetworkCredential("id#domain.com", "IDPass");
//smtp.Credentials = new System.Net.NetworkCredential(sMailEnvioEmpresaServicio , sClaveEmpresaServicio);
smtp.EnableSsl = true;
smtp.SendAsync(correo, null);
//smtp.Send(correo);
The error is: "Unable to send to all recipients"
Why in the localhost works and in the host No?
Error: System.Net.Mail.SmtpFailedRecipientsException: Unable to send to all recipients.
System.Net.Mail.SmtpFailedRecipientException: The mailbox is unavailable.
The server response was: 5.7.1 <csc#cscdecision.com> Access to <ccruz#decision.com.ec> not allowed
have you specified what port the mail server is on?
i.e smtp.port = 25 (or a different port for SSL)
it's possible your host is blocking the port you are using.
Are you sending to same domain name .? If yes so you have to configure that this domain has a remote mail server not localy .
This is common in cpanel hosts .when the domain has a remote mail server

Resources