Email cannot be sent with sendgrid(C#) and no trace of Exceptions - c#

I use the SendAsync method in my code to trigger Emails. The Email Code is printed below.
public async Task SendAsync(IdentityMessage message) {
if (message.Destination != null)
await configSendGridasync(message);
}
private async Task configSendGridasync(IdentityMessage message) {
var myMessage = new SendGridMessage();
myMessage.AddTo(message.Destination);
myMessage.From = new MailAddress(ConfigurationManager.AppSettings["mailAccount"], "XYC Social");
myMessage.Subject = message.Subject;
myMessage.Text = message.Body;
myMessage.Html = message.Body;
var credentials = new NetworkCredential(
ConfigurationManager.AppSettings["mailAccount"],
ConfigurationManager.AppSettings["mailPassword"]
);
// Create a Web transport for sending email.
var transportWeb = new Web(credentials);
// Send the email.
if (transportWeb != null) {
await transportWeb.DeliverAsync(myMessage);
} else {
Trace.TraceError("Failed to create Web transport.");
await Task.FromResult(0);
}
}
In the controller I use below code to trigger the Email.
public async Task < ActionResult > ForgotPassword(XYCSocial.Models.ManageUserViewModel model) {
IdentityMessage msg = new IdentityMessage {
" Message",
Subject = "Reset Password",
Destination = result.Email
};
try {
await _emailService.SendAsync(msg);
} catch (Exception ex) {
ViewBag.Status = "Error : " + ex.Message;
throw;
}
TempData["Success"] = " Some Message";
return RedirectToAction("Login");
}
} else {
TempData["Failed"] = "Please enter valid User name";
return RedirectToAction("Login");
}
} catch (Exception) {
TempData["Failed"] = "Email Send Failed..Please Try After Some Time";
return RedirectToAction("Login");
However When I call the SendAsync method in the controller for triggering emails it just executes without an error but the Email Is never sent.
Finally after a long time it says:
Email Send Failed
From the above TempData["Failed"] tag. I had verified the suppressions folder in the sendgrid account but there is no sign of Spam, or bad email address, or block, etc.
This same code was working until Feb 17th, 2017 but just doesn't work after that.

I too had the same issues using similar code. What I found tonight was an updated sample on the sendgrid GitHub page https://github.com/sendgrid/sendgrid-csharp
This is for the V3 version of Sendgrid Mail.
I can confirm that using this code with an Azure hosted MVC 5 solution works:
var apiKey = Environment.GetEnvironmentVariable("NAME_OF_THE_ENVIRONMENT_VARIABLE_FOR_YOUR_SENDGRID_KEY");
var client = new SendGridClient(apiKey);
var from = new EmailAddress("test#example.com", "Example User");
var subject = "Hello World from the SendGrid CSharp SDK!";
var to = new EmailAddress("test#example.com", "Example User");
var plainTextContent = "Hello, Email!";
var htmlContent = "<strong>Hello, Email!</strong>";
var msg = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent);
var response = await client.SendEmailAsync(msg);
You would need to replace your entire Config method and add your environment variable inside the Azure portal manager (which you need to get from the Sendgrid site)

Related

Using Gmail SMTP OAUTH2 to send email: error JWT has expired

I created a ClientID & Client Secret (using this guide) to authenticate a desktop application (C#/.NET) to send emails from a Gmail account, with Gmail SMTP OAUTH because Google will no longer support less secure apps to send e-mail.
The first time application ran, browser was open and i had need to enter on accounts.google.com with my credential and mail has been sent.
After i receveid an Error "JWT is expired" when i try to execute
var jwtPayload = GoogleJsonWebSignature.ValidateAsync(asyncUserCredential.Token.IdToken).Result;
I can't able to understand how it works and how i can obtain a refreshed token for passing to ValidateAsync method.
This is code used:
private async Task AuthenticateAsync()
{
bool expired;
string mytoken;
try
{
string CLIENT_ID = "41527eeeeee489-xxxxxxxxxxxxxxxxxxxusercontent.com";
asyncUserCredential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
new ClientSecrets
{
ClientId = CLIENT_ID,
ClientSecret = "GOCXXXXXXXXXXXXXXXXXXX"
},
new[] { "email", "profile", "https://mail.google.com/" },
"user",
CancellationToken.None
);
var sFromMailAddress = "office#gmail.com";
var jwtPayload = GoogleJsonWebSignature.ValidateAsync(asyncUserCredential.Token.IdToken).Result;
var mailMessage = new MimeMessage();
mailMessage.From.Add(new MailboxAddress("Office", sFromMailAddress));
mailMessage.To.Add(new MailboxAddress("Frank", "someone#gmail.com"));
mailMessage.Subject = "Automated Mail with OAuth";
mailMessage.Body = new TextPart("plain")
{
Text = "Hello"
};
using (var client = new SmtpClient())
{
client.Connect("smtp.gmail.com", 587, SecureSocketOptions.StartTls);
// use the access token
var oauth2 = new SaslMechanismOAuth2(sFromMailAddress, asyncUserCredential.Token.AccessToken);
client.Authenticate(oauth2);
client.Send(mailMessage);
client.Disconnect(true);
}
}
catch (Exception ex)
{
string msg = ex.Message;
if (ex.InnerException != null)
msg = ex.InnerException.Message;
if (msg.Contains("JWT has expired"))
{
expired = true;
}
else if (msg.Contains("JWT invalid"))
{
//XtraMessageBox.Show("JWT invalid" , "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
else
{
//XtraMessageBox.Show(msg, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
//return string.Empty;
}
}
For sending email used:
using MailKit.Net.Smtp;
using MimeKit;
using MailKit.Security;

Sending emails consistently returns 5.7.3 Authentication unsuccessful code or some variation of an authentication failure

I can't for the life of me figure this out. Currently using MailKit + Godaddy email accounts (through Office365).
I don't have 2FA enabled, user/pass is correct. No matter what combination of settings I do, email doesn't work.
This is the code I'm using currently (I've also tried System.Net's SmtpClient using a ton of different setups, and nothing works)-
public async Task SendEmailAsync(string email, string subject, string htmlMessage)
{
using var client = new SmtpClient();
await client.ConnectAsync(Host, Port, SecureSocketOptions.StartTls);
await client.AuthenticateAsync(User, Pass);
var message = new MimeMessage();
message.From.Add(new MailboxAddress("", FromAddress));
message.To.Add(new MailboxAddress("", email));
message.Subject = subject;
message.Body = new TextPart(MimeKit.Text.TextFormat.Html) { Text = htmlMessage };
try
{
await client.SendAsync(message);
await client.DisconnectAsync(true);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
throw;
}
}

Failed to send email using outlook office365 c# code

I have written below code to send email using Outlook Office365.
ExchangeService myService = new ExchangeService(ExchangeVersion.Exchange2010_SP1);
myService.Credentials = new WebCredentials(sender_mailId,sender_password);
try
{
string serviceUrl = <<service url>> // This URL
myService.Url = new Uri(serviceUrl);
EmailMessage emailMessage = new EmailMessage(myservice);
emailMessage.Subject = "Subject test ";
emailMessage.Body = new MessageBody("Testing Exchange Web Service API");
emailMessage.ToRecipients.Add(to_email_id);
emailMessage.Send();
}
catch (SmtpException exception)
{
string msg = "Mail cannot be sent (SmtpException):";
msg += exception.Message;
throw new Exception(msg);
}
What web service URL should be used?
The below code is worked to send or save to email draft.
static void CheckEmail()
{
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013);
service.Credentials = new WebCredentials(senderEmailId, password);
service.AutodiscoverUrl(senderEmailId, RedirectionUrlValidationCallback);
EmailMessage emailMessage = new EmailMessage(service);
emailMessage.Subject = "Test office 365 project draft ";
emailMessage.Body = new MessageBody("Testing Exchange Web Service API");
emailMessage.ToRecipients.Add(emailTo);
//send email
emailMessage.Send();
//save to draft
emailMessage.Save(WellKnownFolderName.Drafts);
}
private static bool RedirectionUrlValidationCallback(string redirectionUrl)
{
// The default for the validation callback is to reject the URL.
bool result = false;
Uri redirectionUri = new Uri(redirectionUrl);
// Validate the contents of the redirection URL. In this simple validation
// callback, the redirection URL is considered valid if it is using HTTPS
// to encrypt the authentication credentials.
if (redirectionUri.Scheme == "https")
{
result = true;
}
return result;
}

Confirmation Email sent through smtp client is not sending the complete url c#

I'm building a confirmation email process after a user registers in my ASP.NET App.
Here's my code:
var code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
var callbackUrl = new Uri(Url.Link("ConfirmEmailRoute", new { userId = user.Id, code = code }));
SmtpClient smtpClient = new SmtpClient("smtp.office365.com", 25);
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = new System.Net.NetworkCredential(credentials, credentials);
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.EnableSsl = true;
MailMessage mail = new MailMessage();
mail.Body = "Please confirm your account by clicking this link: <a href=\""
+ callbackUrl + "\">link</a>";
mail.From = new MailAddress(Address, App);
mail.To.Add(new MailAddress(user.Email));
//mail.CC.Add(new MailAddress("MyEmailID#gmail.com"));
smtpClient.Send(mail);
Here's the confirm email:
[HttpGet]
[Route("ConfirmEmail", Name = "ConfirmEmailRoute")]
public async Task<IHttpActionResult> ConfirmEmail(string userId = "", string code = "")
{
//var _result = XElement.Parse(success).Value;
if (string.IsNullOrWhiteSpace(userId) || string.IsNullOrWhiteSpace(code))
{
ModelState.AddModelError("", "User Id and Code are required");
return BadRequest(ModelState);
}
IdentityResult result = await UserManager.ConfirmEmailAsync(userId, code);
if (result.Succeeded)
{
var response = new JObject();
response.Add(new JProperty("Email Verified", "You can now log in to the app."));
return Ok(response);
}
else
{
return GetErrorResult(result);
}
}
This email is being sent successfully on desktop app and on Gmail app on mobile phone.
For apple devices, the mail app doesn't take the link fully
I.E.
callbackurl is not all included in the Link
Thanks in advance.
I just had to add :
mail.IsBodyHtml = true;
the link was sent was fully.

How can I silently send Outlook email?

I've got this code that sends an email with attachment[s]:
internal static bool EmailGeneratedReport(List<string> recipients)
{
bool success = true;
try
{
Microsoft.Office.Interop.Outlook.Application app = new Microsoft.Office.Interop.Outlook.Application();
MailItem mailItem = app.CreateItem(OlItemType.olMailItem);
Recipients _recipients = mailItem.Recipients;
foreach (string recip in recipients)
{
Recipient outlookRecipient = _recipients.Add(recip);
outlookRecipient.Type = (int)OlMailRecipientType.olTo;
outlookRecipient.Resolve();
}
mailItem.Subject = String.Format("Platypus Reports generated {0}", GetYYYYMMDDHHMM());
List<String> htmlBody = new List<string>
{
"<html><body><img src=\"http://www.platypus.com/wp-content/themes/duckbill/images/pa_logo_notag.png\" alt=\"Pro*Act logo\" ><p>Your Platypus reports are attached.</p>"
};
htmlBody.Add("</body></html>");
mailItem.HTMLBody = string.Join(Environment.NewLine, htmlBody.ToArray());
. . . // un-Outlook-specific code elided for brevity
FileInfo[] rptsToEmail = GetLastReportsGenerated(uniqueFolder);
foreach (var file in rptsToEmail)
{
String fullFilename = Path.Combine(uniqueFolder, file.Name);
if (!File.Exists(fullFilename)) continue;
if (!file.Name.Contains(PROCESSED_FILE_APPENDAGE))
{
mailItem.Attachments.Add(fullFilename);
}
MarkFileAsSent(fullFilename);
}
mailItem.Importance = OlImportance.olImportanceHigh;
mailItem.Display(false);
}
catch (System.Exception ex)
{
String exDetail = String.Format(ExceptionFormatString, ex.Message,
Environment.NewLine, ex.Source, ex.StackTrace, ex.InnerException);
MessageBox.Show(exDetail);
success = false;
}
return success;
}
However, it pops up the email window when ready, which the user must respond to by either sending or canceling. As this is in an app that sends email based on a timer generating reports to be sent, I can't rely on a human being present to hit the "Send" button.
Can Outlook email be sent "silently"? If so, how?
I can send email silently with gmail:
private void EmailMessage(string msg)
{
string FROM_EMAIL = "sharedhearts#gmail.com";
string TO_EMAIL = "cshannon#platypus.com";
string FROM_EMAIL_NAME = "B. Clay Shannon";
string TO_EMAIL_NAME = "Clay Shannon";
string GMAIL_PASSWORD = "theRainNSpainFallsMainlyOnDonQuixotesHelmet";
var fromAddress = new MailAddress(FROM_EMAIL, FROM_EMAIL_NAME);
var toAddress = new MailAddress(TO_EMAIL, TO_EMAIL_NAME);
string fromPassword = GMAIL_PASSWORD;
string subject = string.Format("Log msg from ReportScheduler app sent
{0}", DateTime.Now.ToLongDateString());
string body = msg;
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)
{
Subject = subject,
Body = body
})
{
smtp.Send(message);
}
}
...but when I do that, I have to supply my gmail password, and I don't really want to do that (expose my password in the source code).
So, how can I gain the benefits of gmailing (silence) and Outlook (keeping my password private)?
If you want the shortest way:
System.Web.Mail.SmtpMail.SmtpServer="SMTP Host Address";
System.Web.Mail.SmtpMail.Send("from","To","Subject","MessageText");
This was code that I was reusing from another project where I wanted the send dialog to display, and for the email only to be sent when the user hit the "Send" button. For that reason, it didn't call "send"
To get the email to send silently/unattended, I just needed to add a call to "mailItem.Send()" like so:
mailItem.Importance = OlImportance.olImportanceHigh;
mailItem.Display(false);
mailItem.Send(); // This was missing

Categories

Resources