How to use Blazor to send email thru Azure website - azure-web-app-service

If I am creating a Blazor App base on Asp.net Host template and I have a paid subscription for Azure. I would like to know how to send an email when user have entered the required info.
Here the code for Asp.netCore and I am not sure how to use it for my case using Blazor to send thru Azure website. Would appreciate if you can provide some reference to read or a sample code to try out.
Thanks
using System.Net.Mail;
MailMessage mailMessage = new MailMessage();
mailMessage.From = new MailAddress("email1#somewebsite.com");
mailMessage.To.Add(new MailAddress("email2#somewebsite.com"));
mailMessage.Subject = "Your subject";
mailMessage.IsBodyHtml = true;
mailMessage.Body = "Email body";
SmtpClient client = new SmtpClient();
client.Credentials = new System.Net.NetworkCredential("email1#somewebsite.com", "password");
client.Host = "smtpout.asia.secureserver.net";
client.Send(mailMessage);

Related

dotnet Core - Using azure AD authentication to retrive data from sharepoint REST API

My project is set up to use azure ad as login(from the dotnet core template). I have successfully managed to log in.
However, i want to use the same logged in user to retrive data from sharepoint rest api.
I have the following method:
public async Task<FileResults> Test()
{
var siteUrl = "https://xxxxx.sharepoint.com";
var username = "xx#xx.no";
var password = "xxxxxx";
var securePassword = new SecureString();
password.ToCharArray().ToList().ForEach(c => securePassword.AppendChar(c));
var credentials = new SharePointOnlineCredentials(username, securePassword);
var handler = new HttpClientHandler();
handler.Credentials = credentials;
var uri = new Uri(siteUrl);
handler.CookieContainer.SetCookies(uri, credentials.GetAuthenticationCookie(uri));
var json = string.Empty;
using (var client = new HttpClient(handler))
{
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose");
var response = await client.GetAsync(siteUrl + "/_api/Web/GetFolderByServerRelativeUrl('/Delte%20dokumenter/Test')/Files");
json = await response.Content.ReadAsStringAsync();
var result = Newtonsoft.Json.JsonConvert.DeserializeObject<Rootobject>(json);
var files = result.FileResults;
return files;
}
}
This is working fine and im getting documents from sharepoint.
But, this is when using hardcoded credentials. How do i use the credentials of the logged in user via azure AD? Do i retrive the accesstoken?
To use the Azure AD Authentication you need to have one of the Authentication flows.
Note: Username/Password flow is not recommended.
After that you will be getting the tokens according to the scopes that are specified and you need to hit the Microsoft Graph Api, internally you need to hit the SharePoint API endpoints according to your requirement.
You can start exploring with this sample

Use the Outlook/Office365 REST API to send mail from connected email address

I am trying to send an email using the Outlook/Office 365 REST API, and I am trying to send it as an address that I have as a "Connected Account". Attempting to send the message returns a `` error. However, the API will let me create a draft with this address.
Additionally, I can send the API-created draft just fine, and I can also create and send messages as this account from the web interface.
Is there a way to authorize the API to be able to send a message as an address for a connected account?
No, the API doesn't support this today. It has to do with the scope of the permissions that you consent to. "Allow this app to send mail as you" covers sending from your account, but not from another account, even if you have been granted access.
Another thing you can think about is to leverage App-only authentication. You can configure a Azure AD App to have App-only authentication. After that, all the request will behalf of that app id and you should be able to delegate that app id to send email to anyone on behalf of the user you want.
The following is the steps:
Create a Azure AD application.
Configure your Azure AD Application to allow App-only token by
following Build service and daemon apps in Office 365. You also
need a certificate for app-only token request.
Go to your Azure AD Application->Configuration, Click "Add
application" to add "Office 365 Exchange Online". Select "Send email
as any user" under "Application permission" dropdown box. It allows
your Azure AD App to have permission to send email on behalf of
someone.
Once you have Azure AD application configured, you can refer the
following code for sending email on behalf of a specific user.
string tenantId = "yourtenant.onmicrosoft.com";
string clientId = "your client id";
string resourceId = "https://outlook.office.com/";
string resourceUrl = "https://outlook.office.com/api/v2.0/users/service#contoso.com/sendmail"; //this is your on behalf user's UPN
string authority = String.Format("https://login.windows.net/{1}", AUTHORITYURL, tenantId);
string certificatPath = #"c:\test.pfx"; //this is your certficate location.
string certificatePassword = "xxxx"; // this is your certificate password
var itemPayload = new
{
Message = new
{
Subject = "Test email",
Body = new { ContentType = "Text", Content = "this is test email." },
ToRecipients = new[] { new { EmailAddress = new { Address = "test#cotoso.com" } } }
}
};
//if you need to load from certficate store, use different constructors.
X509Certificate2 certificate = new X509Certificate2(certficatePath, certificatePassword, X509KeyStorageFlags.MachineKeySet);
AuthenticationContext authenticationContext = new AuthenticationContext(authority, false);
ClientAssertionCertificate cac = new ClientAssertionCertificate(clientId, certificate);
//get the access token to Outlook using the ClientAssertionCertificate
var authenticationResult = await authenticationContext.AcquireTokenAsync(resourceId, cac);
string token = authenticationResult.AccessToken;
//initialize HttpClient for REST call
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
client.DefaultRequestHeaders.Add("Accept", "application/json");
//setup the client post
HttpContent content = new StringContent(JsonConvert.SerializeObject(itemPayload));
//Specify the content type.
content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json;odata=verbose");
HttpResponseMessage result = await client.PostAsync(url, content);
if(result.IsSuccessStatusCode)
{
//email send successfully.
}else
{
//email send failed. check the result for detail information from REST api.
}
For a complete explanation, please reference to my blog Send email on behalf of a service account using Office Graph API
I hope it helps and let me know if you have questions.

How to Authenticate and Authorize Asp.Net Web application through QuickBooks?

how to Authenticate and Authorize Asp.Net Web application through QuickBooks.
I want to integrate QuickBooks Accounts System in ASP.NET web Application I have successfully make developer account on quickbooks and make an app and got consumer key, consumer Secret and App Token and all URL's
Know I need some asp.net web api code snipped to successfully authenticate and authorize my web user's and than show there accounting detail
Please help me i Google alot but have no success.
I'm Strange this form is 0% active related to quickbooks API's or etc, after alot of struggling i found an answer of above mention question,
Download Quickbooks IPP.NET SDK it will provide you different classes for CURD.
var appToken = "";
var consumerKey = "";
var consumerSecret = "";
// the above 3 fields you can get when create your app on quickbook go to My app----> select youre app--->goto KEYS
var accessToken = "";
var accessTokenSecret = "";
// this two tookens you will get from URL on the same above page
var realmId = "1400728630"; //1400728630
// this is youre company ID which can be used when you create youre //company on freshbook
var serviceType = IntuitServicesType.QBO;
var validator = new OAuthRequestValidator(accessToken, accessTokenSecret, consumerKey, consumerSecret);
var context = new ServiceContext(appToken,realmId, serviceType, validator);
var service = new DataService(context);
try
{
Customer customer = new Customer();
//Mandatory Fields
customer.GivenName = "Mary";
customer.Title = "Ms.";
customer.MiddleName = "Jayne";
customer.FamilyName = "Cooper";
service.AddAsync(customer);
//service.Add(entity);
}catch(Exception ex)
{
System.Console.WriteLine(ex);
}

Windows Azure worker role and SendGrid "Bad Key Path!" Error

I'm trying to use SendGrid to send an email from an Azure worker role every time there are certain exceptions, but I can't get the email to send. I am using SendGridMail version 6.1.0.0 and SendGrid.SmtpApi version 1.3.1.0 which I installed via nuget and .Net 4.5. I am currently debugging locally with plans to deploy to Azure if i can get the emails to successfully send.
SendGridMessage myMessage = new SendGridMessage();
List<String> recipients = new List<String> { #"John Doe <johnd#outlook.com>", #"Peter Howe <perterhowe#gmail.com>" };
myMessage.AddTo(recipients);
myMessage.From = new MailAddress("myemail#test.com");
myMessage.Subject = "Error in Update";
myMessage.Text = "TESTING 123";
string username = XXXXXX;
string password = XXXXXXX;
// Create credentials, specifying your user name and password.
var credentials = new NetworkCredential(username, password);
// Create an Web transport for sending email.
var transportWeb = new Web(credentials);
// Send the email.
await transportWeb.DeliverAsync(myMessage);
As far as I can see I'm not getting any errors except when I debug and look at myMessage the Header has an error.
When I tried initializing a new empty header (var header = new Header();) I noticed there were still errors on that
To = 'header.To' threw an exception of type 'System.ArgumentException' Message = "Bad key path!"
Does anyone know what this means? Or if this could be causing the emails not to send?
The answer to your other question actually uses SendGrid:
Alerts for exceptions in an Azure worker role
There are three globalvariables:
public const string SmtpServerHost = "smtp.sendgrid.net";
public const string SmtpServerUserName = "[useridfromsendgrid#azure.com]";
public const string SmtpServerPassword = "[password from sendgrid]";
You actually do not need to use the SDK, just setup the account in Azure portal, and save your creds in your project.
You can send emails locally, but if you are on a work network, the firewall may block the emails from being sent. The code I posted I placed in an email service in my namespace.
It has be deployed to Azure to work. It won't work locally.

Identity 2.1 email service

I am developing a MVC 5 internet application, and am wishing to send an email using the SendGrid service when my application is deployed to Azure.
I have found some resource links, yet each different code implementation that I use, sends the email very slowly. I have chosen to use the code from this link: http://www.codeproject.com/Articles/762427/ASP-NET-Identity-Setting-Up-Account-Validation-and
Here is my code:
public class EmailService : IIdentityMessageService
{
public Task SendAsync(IdentityMessage message)
{
// Credentials:
var sendGridUserName = "myusername";
var sentFrom = "test#email.com";
var sendGridPassword = "mypassword";
// Configure the client:
var client =
new System.Net.Mail.SmtpClient("smtp.sendgrid.net", Convert.ToInt32(587));
client.Port = 587;
client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
// Creatte the credentials:
System.Net.NetworkCredential credentials =
new System.Net.NetworkCredential(sendGridUserName, sendGridPassword);
client.EnableSsl = true;
client.Credentials = credentials;
// Create the message:
var mail =
new System.Net.Mail.MailMessage(sentFrom, message.Destination);
mail.Subject = message.Subject;
mail.Body = message.Body;
// Send:
return client.SendMailAsync(mail);
}
}
The email takes many minutes to send. Why is this? How fast should the email be sent on average, and do I need to optimize my code in any way? Also, rather than using SendGrid, is there a better resource to use that I should use?
Thanks in advance.
Somewhere on Sendgrid documentation (can't find it now unfortunately) I have seen recommendation that if you use their REST API endpoints instead of SMPT, the emails will arrive quicker. And Sendgrid provides C# library to use their API. Give it a go.
It's possible SendGrid is deferring or delaying your sends. Is there any defer or delay activity in your SendGrid dashboard?
You can also connect to the SendGrid Webhook Events to see exactly what's going on with your emails.

Resources