I am unable to send emails on a MVC4 Web App that I configured on Azure. I am being able to send emails locally on my machine, but when I upload the code to my azure app in the cloud, the mail delivery doesn't say it fails, but emails are not delivered, SendGrid doesn't report that the mail was sent on its dashboard either.
Has someone ran into similar issues? Have looked into similar questions with no exact answer.
I did follow the instructions of this article (https://azure.microsoft.com/en-us/documentation/articles/sendgrid-dotnet-how-to-send-email/#reference) without success. Have tried also to the send the emails thru the SendGrid class libraries and by using plain System.Net.Mail.
Any help is appreciated.
Code:
Thanks for the reply. I am using Web.DeliverAsync, this is the code I am using:
// Create network credentials to access your SendGrid account
var username = System.Configuration.ConfigurationManager.AppSettings["smtpUser"];
var pswd = System.Configuration.ConfigurationManager.AppSettings["smtpPass"];
var credentials = new NetworkCredential(username, pswd);
// Create an Web transport for sending email.
SendGrid.Web transportWeb = new SendGrid.Web(credentials);
//var apiKey = System.Configuration.ConfigurationManager.AppSettings["sendgrid_api_key"];
var apiKey = "apikey";
SendGridMessage msg = new SendGridMessage();
msg.Subject = "...";
msg.AddTo(model.Email);
msg.Html = body;
msg.From = new MailAddress("...");
try
{
await transportWeb.DeliverAsync(msg);
}
catch (Exception e)
{
e.ToExceptionless().Submit();
ViewBag.ErrorMsg = e.Message;
return View("Error");
}
Try this:
var apiKey = System.Configuration.ConfigurationManager.AppSettings["sendgrid_api_key"];
// Create an Web transport for sending email.
SendGrid.Web transportWeb = new SendGrid.Web(apiKey);
SendGridMessage msg = new SendGridMessage();
msg.Subject = "...";
msg.AddTo(model.Email);
msg.Html = body;
msg.From = new MailAddress("...");
try
{
await transportWeb.DeliverAsync(msg);
}
catch (Exception e)
{
//e.ToExceptionless().Submit();
ViewBag.ErrorMsg = e.Message;
return View("Error");
}
Also what version of the SendGrid C# library are you using? Make sure it's version 6.3.x or later.
Related
I.m working on a Windows app where the user has to enter a password. I also have a "Forgot Password" link. on the window. When that's clicked, I have the user enter their email address and click a Submit button. Every time they enter an email address and click the button, I get the error message:
SmtpException has occured: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.0 Authentication Required.
The code I'm using is:
try
{
Cursor = Cursors.WaitCursor;
MailAddress from = new MailAddress("bgatt64#gmail.com", "Bob Gatto");
MailAddress to = new MailAddress("bgatto64#yahoo.com", "Bob Gatto");
MailMessage eMsg = new MailMessage(from, to);
eMsg.Subject = "Your Password Renewal Request";
eMsg.IsBodyHtml = true;
eMsg.Body = "This is the body.";
SmtpClient eClient = new SmtpClient("smtp.gmail.com", 587);
eClient.EnableSsl = true;
eClient.UseDefaultCredentials = true;gmail
// The following email and password used is that of my own gmail email
// that I use for my own personal email.
eClient.Credentials = new System.Net.NetworkCredential("<MyOwnEmail#gmail.com>", "<MyPassword>");
eClient.Send(eMsg);
}
catch (SmtpException ex)
{
throw new ApplicationException("SmtpException has occurred: " + ex.Message);
}
catch (Exception ex)
{
throw ex;
}
What else needs to be done?
You cannot use your plain google account password to authenticate to Gmail SMTP server anymore as Google requires two-step authentication now.
You'll need to use the App Password instead:
Go to https://myaccount.google.com/security and turn on Two Step verification
Click "App Passwords"
Request a new password for the Mail application on the Windows Computer
You'll get the string with the 4 groups of characters. Now you need to use it in your code:
eClient.Credentials = new System.Net.NetworkCredential("<MyOwnEmail#gmail.com>", "<App Password>");
You can find more info Here
After the removal of less secure apps you can no longer use your actual google password to connect to the smpt server you need to create an apps password.
How to create a Apps Password for connecting to Google's SMTP server.
using System;
using System.Net;
using System.Net.Mail;
namespace GmailSmtpConsoleApp
{
class Program
{
private const string To = "[redacted]#gmail.com";
private const string From = "[redacted]#gmail.com";
private const string GoogleAppPassword = "";
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);
}
}
}
Note: if you are trying to connect users then you could also use Xoauth2 but using an apps password is far easer solution.
I have an Office 365 Family subscription (thus using outlook.com) and are trying to send email from a C# application I'm working on. Does anybody know if this is even possible?
From my research there seems to be a lot of people having issue with this approach but I'm trying hard to find out if it's supported
There are different ways of doing the required job:
Use standard .net mechanisms, the same question was posted here:
using (SmtpClient client = new SmtpClient()
{
Host = "smtp.office365.com",
Port = 587,
UseDefaultCredentials = false, // This require to be before setting Credentials property
DeliveryMethod = SmtpDeliveryMethod.Network,
Credentials = new NetworkCredential("alias#fulldomain.com", "password"), // you must give a full email address for authentication
TargetName = "STARTTLS/smtp.office365.com", // Set to avoid MustIssueStartTlsFirst exception
EnableSsl = true // Set to avoid secure connection exception
})
{
MailMessage message = new MailMessage()
{
From = new MailAddress("alias#fulldomain.com"), // sender must be a full email address
Subject = subject,
IsBodyHtml = true,
Body = "<h1>Hello World</h1>",
BodyEncoding = System.Text.Encoding.UTF8,
SubjectEncoding = System.Text.Encoding.UTF8,
};
var toAddresses = recipients.Split(',');
foreach (var to in toAddresses)
{
message.To.Add(to.Trim());
}
try
{
client.Send(message);
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
The SmtpClient is usable in .NET Core, but its use isn't recommended. Instead, consider using https://github.com/jstedfast/MailKit .
Use Graph API.
And for anybody else having problems with using smtp.office365.com and sending email through code. You need to add an "app password" in your Microsoft Account. The regular password you use to login to outlook.com will not work
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've been working with Microsoft graph API to receive and reply to the mail.
I've successfully received and send mails, but as per Graph API docs in reply only a comment can be passed.
https://learn.microsoft.com/en-us/graph/api/message-createreply?view=graph-rest-1.0&tabs=cs
I've developed the send mail code as shown below:-
IList<Recipient> messageToList = new List<Recipient>();
User currentUser = client.Me.Request().GetAsync().Result;
Recipient currentUserRecipient = new Recipient();
EmailAddress currentUserEmailAdress = new EmailAddress();
EmailAddress recepientUserEmailAdress = new EmailAddress();
currentUserEmailAdress.Address = currentUser.UserPrincipalName;
currentUserEmailAdress.Name = currentUser.DisplayName;
messageToList.Add(currentUserRecipient);
try
{
ItemBody messageBody = new ItemBody();
messageBody.Content = "A sample message from Ashish";
messageBody.ContentType = BodyType.Text;
Message newMessage = new Message();
newMessage.Subject = "\nSample Mail From Ashish.";
newMessage.ToRecipients = messageToList;
newMessage.CcRecipients = new List<Recipient>()
{
new Recipient
{
EmailAddress = new EmailAddress
{
Address = "abc.xyz#xxxx.com"
}
}
};
newMessage.Body = messageBody;
client.Me.SendMail(newMessage, true).Request().PostAsync();
Console.WriteLine("\nMail sent to {0}", currentUser.DisplayName);
}
catch (Exception)
{
Console.WriteLine("\nUnexpected Error attempting to send an email");
throw;
}
This code is working fine!!
Can someone please share how I can Reply to a mail with attachment and mailbody like I'm able to do in Send mail.
Thanks in advance.
You have to create a reply, add the attachment, and then send the message. With the basic basic /reply endpoint you cant do it.
E.g.:
Create the message draft using POST request
As a response you will get the whole message structure with id set to something like AQMkADAwATMwMAItMTJkYi03YjFjLTAwAi0wMAoARgAAA_hRKmxc6QpJks9QJkO5R50HAP6mz4np5UJHkvaxWZjGproAAAIBDwAAAP6mz4np5UJHkvaxWZjGproAAAAUZT2jAAAA. Lets refer to it as {messageID}.
After that you can create an attachment using POST request to https://graph.microsoft.com/beta/me/messages/{messageID}/attachments
-After step 2 you will see created message in your mailbox Drafts folder. To send it use https://graph.microsoft.com/beta/me/messages/{messageID}/send
Hope it helps.
can any one help me how to send email from asp.net core application from outlook. I'm able to send emails from gmail using MailKit but its failing with outlook
Following is the code i'm using
string FromAddress = "fromemailadress";
string FromAdressTitle = "Email from ASP.NET Core 1.1";
//To Address
string ToAddress = "Toemailadress";
string ToAdressTitle = "Microsoft ASP.NET Core";
string Subject = "Hello World - Sending email using ASP.NET Core 1.1";
string BodyContent = "ASP.NET Core was previously called ASP.NET 5. It was renamed in January 2016. It supports cross-platform frameworks ( Windows, Linux, Mac ) for building modern cloud-based internet-connected applications like IOT, web apps, and mobile back-end.";
//Smtp Server
string SmtpServer = "smtp.live.com";
//Smtp Port Number
int SmtpPortNumber = 587;
var mimeMessage = new MimeMessage();
mimeMessage.From.Add(new MailboxAddress(FromAdressTitle, FromAddress));
mimeMessage.To.Add(new MailboxAddress(ToAdressTitle, ToAddress));
mimeMessage.Subject = Subject;
//mimeMessage.Body = new TextPart("plain")
//{
// Text = BodyContent
//};
var bodyBuilder = new BodyBuilder();
bodyBuilder.HtmlBody = #"<b style='color:blue'>This is bold and this is <i>italic</i></b>";
mimeMessage.Body = bodyBuilder.ToMessageBody();
using (var client = new SmtpClient())
{
client.Connect(SmtpServer, SmtpPortNumber, false);
// Note: only needed if the SMTP server requires authentication
// Error 5.5.1 Authentication
client.Authenticate("Email", "Password");
client.Send(mimeMessage);
Console.WriteLine("The mail has been sent successfully !!");
Console.ReadLine();
client.Disconnect(true);
}
its throwing error smptp server has unexpectedly disconnected
Most likely you are hitting a bug in the NTLM authentication code which seems to not work on some versions of Exchange.
You can disable NTLM auth by doing:
client.AuthenticationMechanisms.Remove ("NTLM");
Call that just before calling the Authenticate method and you will likely be fine.