Send gmail from web application hosted on Azure - email

Newbie to Azure, but got my application successfully published to the cloud as well as my needed database backends (SQL server).
Everything within the application is working as expected except email functionality. I am sending out email alerts via a gmail account, but they do not appear to get sent out. The application does not crash and trying to configure remote debugging has proven difficult.
This is the snippet I am using to send out my emails:
//Parse html document which will show in outgoing email
StreamReader reader = new StreamReader(HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["template"]));
string body = reader.ReadToEnd();
//Populate placeholders with message variables
body = body.Replace("<%holder%>", value);
...Omitted for brevity
try
{
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
};
using (var message = new MailMessage(fromAddress, toAddress)
{
IsBodyHtml = true,
Subject = subject,
Body = body,
})
{
smtp.Send(message);
}
}
Application didn't crash, so no error message to go off of. So I thought maybe it wasn't able to grab the file in the lines:
StreamReader(HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["template"]));
string body = reader.ReadToEnd();
So I tried just sending a hardcoded string as a test:
string body = "test";
Still no email received and no error message to go off of. I'm new to azure web hosting, but is there some configuration I could be missing here? Does Azure allow sending email through third party email clients? Fyi - the above code works against localhost.

Sending e-mail from a public cloud is not as trivial as some people believe. There are a lot of things to figure out in order to not get blacklisted. Especially when you intend to use a public mail service.
My first guess is that Azure Data Center IP addresses (or the one you are hosted on) might be blacklisted by mail servers (including Microsoft's very own Office 365).
I have to also mention that recommended way for sending e-mail from an Application hosted in Azure is by using SendGrid. They have a free tier. More information from Microsoft on that subject, can be found here.
The only way to troubleshoot the exact cause of your problem is to contact GMail support and ask them if they block in any way network clients connecting from Azure cloud. Or create a VM in the same Data Center where your web application lives, install some free / trial Mail client, configure it with Google Mail and try to send e-mails. The result most probably will be same as with your application.

Related

Send mail with Nuxt trough Sendgrid

I have a simple vuetify contact form and I want to send this forms by email.
I have tried to use a method to send the email, but it does not work, because its on client side. So I get CORS issues.
Here's my code:
async send() {
if (this.$refs.form.validate()) {
try {
const sgMail = require("#sendgrid/mail");
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
const msg = {
to: "test#example.com",
from: "me#mydomain.com",
subject: "Sending with SendGrid is Fun",
text: "and easy to do anywhere, even with Node.js",
html: "<strong>and easy to do anywhere, even with Node.js</strong>"
};
sgMail.send(msg);
}
}
}
Is Express (or an other backend) required? Is there a way to make it work using a middleware?
EDIT
Apparently, it's just not possible: https://github.com/sendgrid/sendgrid-nodejs/issues/730
The CORS policy from Sendgrid does not allow you to use their API from the browser (The 'Access-Control-Allow-Origin' header has a value 'https://sendgrid.api-docs.io').
Quoted from https://sendgrid.com/docs/for-developers/sending-email/cors/ :
In SendGrid's case, we do not allow our customers to make a browser-based call to our v3/mail/send endpoint. (...)
You can create a server-based application, which will protect your API keys from being released to the world. Languages like NodeJS, PHP, Ruby, Python, C#, Go, and Java, and others can be implemented to make calls to the API from the security of a locked down server environment.
You have to send the email from a server, which is a good thing since your API Key would be exposed by the browser otherwise.
If you are using Nuxt in SSR mode (with Node running), I guess you could create a "Server Middleware" ( https://nuxtjs.org/api/configuration-servermiddleware ), for example with a path like "/api/mail", that will send the email.
If you are using nuxt-generate to create a static site, you can use a "function as a service", with something like "https://webtask.io/", to create a small node script; that you can trigger by url from your client to send the email.

S22 imap fetch mails from office365

I'm using s22.Imap referance for fetch new mails from server. While read exchange server everything was perfect. But we were moved to office365. Now I can't read new mails from my project. Here is small codes.
using (ImapClient client = new ImapClient("outlook.office365.com", 993, user, pass, AuthMethod.Login, true)) {
// Returns a collection of identifiers of all mails matching the specified search criteria.
IEnumerable<uint> uids = client.Search(SearchCondition.New());
// Download mail messages from the default mailbox.
IEnumerable<MailMessage> messages = client.GetMessages(uids);
foreach (MailMessage item in messages) { blablabla }
This part return this error : The stream could not be read.
Lastly I'm using this codes in windows service application. So I'm not clearly debuging.
Is anyone help me ?
Office365 does not support AuthMethod.Login. Try AuthMethod.Plain or try using a different IMAP library like my MailKit library which is more actively maintained.
Hope that helps.
its possible but I think that the suscription of the account should be
Exchange Online, instead of a classic suscription
I do the same with S22 library, but we request to change the configuration of the mail to accept imap conection

Office365: Sending a message using SMTP and keeping a copy on the server

I am sending emails using the .NET SmtpClient via Office 365.
The emails are sent without problem, however the messages are not later shown in sent items.
Is there a way to configure either O365 or SmtpClient to retain a copy of any message sent through SMTP in the mailbox?
Martin.
the Exchange Web Services Managed API might solve your issue. There's a method named SendAndSaveCopy() - shown in the below sample:
private void sendEmail()
{
ExchangeService myservice = new ExchangeService();
myservice.AutodiscoverUrl("name#domain.com");
EmailMessage mymessage = new EmailMessage(myservice);
mymessage.Subject = "mysubject";
mymessage.Body = "mybody";
mymessage.ToRecipients.Add("myrecipient");
mymessage.Save();
mymessage.SendAndSaveCopy();
}
You can get the Exchange Web Services Managed API here:
https://msdn.microsoft.com/en-us/library/office/mt674770.aspx
Please also find an example how to use den Exchange Web Services Managed API here:
https://code.msdn.microsoft.com/office/Send-Email-with-Exchange-50189e57
Please let me know if this works for you.
Best,
Sebastian

cakephp emails not working

my problem is:
in the controller I have:
var $components = array('Email');
the method to send emails looks like this:
function send_emails() {
$this->Email->from = 'Somebody <somebody#example.com>';
$this->Email->to = 'Somebody Else <myspamplace#centrum.cz>';
$this->Email->subject = 'Test';
$this->Email->send('Hello message body!');
}
I am using Cake 1.3 and running it on localhost with Apache 2.2.11 and PHP5. Do you guys have any idea why it doesn't work?
When I put
$this->Email->delivery = 'debug';
in the code, it displays the email info and it seems like everything is ok.
Do you have any ideas what can be the reason why it doesn't send email?
If you're developing on a remote server, i.e. a hosting server, then that should work as it'll pick up the default email.
As you're not, you have to give the mail component some email capability. You can do this by, for example, feeding in your gmail (or whatever) smtp details, i.e. server, login, password.
/* SMTP Options for GMAIL */
$this->Email->smtpOptions = array(
'port'=>'465',
'timeout'=>'30',
'auth' => true,
'host' => 'ssl://smtp.gmail.com',
'username'=>'your_username#gmail.com',
'password'=>'your_gmail_password',
);
/* Set delivery method */
$this->Email->delivery = 'smtp';
See http://book.cakephp.org/view/1290/Sending-A-Message-Using-SMTP
If you're not sure what credentials to use, look it up in your email provider's help or faq. Typically it can be found by searching for how to set up Outlook or Thunderbird.
Are you sending from a windows server? If so, have you properly setup your MTA in the php ini? Can you send mail using the mail() function?
If you are on windows and need an MTA, hMail is great for development, note that many hosts will reject mail from your local machine a spam so don't use on production without an MX record, domain keys etc.
You need an SMTP server to send email. If you are trying to send it from your localhost, two good alternatives are:
FreeSMTP: A Windows-based tool that lets your computer act like an SMTP Server
Gmail: You can use your Gmail address for testing purposes.
You need to follow the instructions to send email using CakePHP through SMTP. You could also modify your php.ini settings to reflect the new settings.
I had the same problem, I forgot to enable ssl on my xampp server, for that it is necessary just to add(or uncomment) extension=php_openssl.dll line in your php.ini file. Hope it helps.

CakePHP Email Does Not Send on Mosso Cloud Sites

I have uploaded a working Cakephp web application to Mosso Cloud Sites hosting. The application is working fine except that emails are no longer being delivered. The site is an exact copy from my previous host, where sending email was working correctly. The app uses the built in Cakephp email component. I have searched Mosso's knowledgebase and followed the directions for php email (htaccess method) here. My script is as follows:
$this->Email->reset();
$this->Email->sendAs = 'html'; // both = html + plain text
$this->Email->to = '"'.$data['Customer']['first_name'].' '.$data['Customer']['last_name'].'" <' . $data['Customer']['email']. '>';
$this->Email->bcc = $this->_generateRecipients($data['Booking']['sales_associate_id']);
$this->Email->from = '<noreply#'.env('HTTP_HOST').'>';
$this->Email->replyTo = '<noreply#'.env('HTTP_HOST').'>';
$this->Email->return = '<noreply#'.env('HTTP_HOST').'>';
$this->Email->subject = 'Rental Receipt';
// Select appropraite email template
switch ($this->Session->read('site_id')) {
case '100':
$this->Email->template = 'vac_receipt1';
break;
case '200':
$this->Email->template = 'vac_receipt2';
break;
}
$this->Email->send();
I would post a comment but don't have the reputations yet..
Anyway, did you check the send() return value? Do you get any errors in your log files? If there are no errors and the return value is fine, you should probably contact the support of your host.
After discussing the issue with the Mosso staff at length one of their linux admins stepped in and after reviewing the code noted that the Mosso Cloud Sites email system does NOT support Bcc or Cc on code generated emails. So since my code was using Bcc to send a copy to our staff as well as to the customer my emails were not being sent and no PHP errors were being thrown.
So if you use Mosso Cloud sites you cannot send emails with Bcc or Cc from code. Lesson learned, but something that should be easier to find in their knowledge base.