Which do i need Sendgrid or Mailkit - to send emails from azure webjob - console-application

Can i use Mailkit to send emails from an azure webjob using an organizational smtp server? Or do i need to use Sendgrid?
Mine is a .net core 1.1 console application which i then hosted as azure webjob.
For some reason, I am not able to get my webjob working with Mailkit using an organizational Smtp server. The job runs successfully, does not log any errors. BUT not able to send mails out..
here is my code that uses mailkit
using (var client = new SmtpClient())
{
try {
// For demo-purposes, accept all SSL certificates (in case the server supports STARTTLS)
client.ServerCertificateValidationCallback = (s, c, h, e) => true;
Logger.LogInformation("Ready to connect to smtp server");
client.Connect(Constants.SMTP_HOST, 25, false);
Logger.LogInformation("connected to smtp server");
// Note: since we don't have an OAuth2 token, disable
// the XOAUTH2 authentication mechanism.
client.AuthenticationMechanisms.Remove("XOAUTH2");
Logger.LogInformation("Ready to send email");
client.Send(message);
}
catch (Exception ex) {
Logger.LogError("An error occurred");
Logger.LogError(ex.StackTrace);
}
finally {
client.Disconnect(true);
}
}

Can i use Mailkit to send emails from an azure webjob using an organizational smtp server?
If you use the organizational smtp server, then should make sure that your email server policy allowed to that.
I test Mailkit in the Azure WebJob with google email. It works correctly on my side. Before that I turn Allow less secure apps: ON for my gmail account
The following is the demo code.
var message = new MimeMessage();
message.From.Add(new MailboxAddress("Tom Gmail", "xx#gmail.com"));
message.To.Add(new MailboxAddress("Tom Hotmail", "xxx#hotmail.com"));
message.Subject = "I am a mail subject";
message.Body = new TextPart("plain")
{
Text = "I am a mail body."
};
using (var client = new SmtpClient())
{
client.Connect("smtp.gmail.com", 587);
// Note: since we don't have an OAuth2 token, disable
// the XOAUTH2 authentication mechanism.
client.AuthenticationMechanisms.Remove("XOAUTH2");
// Note: only needed if the SMTP server requires authentication
client.Authenticate("sunguiguan#gmail.com", "#WSX3edc");
client.Send(message);
client.Disconnect(true);
}
Console.WriteLine("send mail successful");
Console.Read();
Or do i need to use Sendgrid?
On my opinon, SendGrid also is a good choice, we also could use the free price tier on the Azure. I also test it on myside. it also works correctly. We also could get more detail info from azure official document.
var apiKey ="ApiKey";//System.Environment.GetEnvironmentVariable("SENDGRID_APIKEY");
var client = new SendGridClient(apiKey);
var msg = new SendGridMessage()
{
From = new EmailAddress("xxx#hotmail.com", "Send Grid"),
Subject = "Hello World from the SendGrid CSharp SDK!",
PlainTextContent = "Hello, Email!",
HtmlContent = "<strong>Hello, Email!</strong>"
};
msg.AddTo(new EmailAddress("xxxx#gmail.com", "Test User"));
client.SendEmailAsync(msg).Wait();
}

Related

AWS IoT Core connection over wss on flutter webapp

I made a flutter web application, it works perfectly with my local broker over ws, the problem starts when I need to connect the application with AWS, I followed the instructions in this video How to connect to AWS IOT with MQTT with AWS Signature Version 4 authentication?
to authenticate but I can't get it to work.
Could you guide me on this, thank you.
part of my code:
Future initMqtt() async {
_client = MqttBrowserClient(host!, '')
..port = port!
..logging(on: true)
..keepAlivePeriod = 20
..onConnected = onConnected
..onDisconnected = onDisconnected
..onSubscribed = onSubscribed
..websocketProtocols = MqttClientConstants.protocolsSingleDefault
..setProtocolV311();
final mqttMsg = MqttConnectMessage()
.withWillTopic('willtopic')
.withWillMessage('Will message')
.startClean()
.withWillQos(MqttQos.atLeastOnce);
_client.connectionMessage = mqttMsg;
return await connectionMqtt();
}

Mail code works in localhost but not on the URL website afterwards

I made a web application on visual studio 2017 for ASP.NET core. It has a contact option where users send me an email. It works perfectly in localhost as I receive the feedback. When I build/release using Azure DevOps onto azure app services in the portal my website at its URL loses the functionality of the email option. I wrote the email code using MailKit, if you guys have a better option that works let me know! Thank you.
var message = new MimeMessage();
message.From.Add(new MailboxAddress(inputEmail));
message.To.Add(new MailboxAddress("myemail"));
message.Subject = "Message from: " + inputName;
message.Body = new TextPart("plain")
{
Text = inputMessage
};
using (var client = new SmtpClient())
{
client.Connect("smtp.gmail.com", 587, false);
client.Authenticate("email", "password");
client.Send(message);
client.Disconnect(true);
};
return RedirectToAction("Index");
mywebsite.azurewebsites.net is currently unable to handle this request.
The problem is that you are using gmail. GMail only allows you to authenticate using SMTP/IMAP/POP3 after you've authenticated via the web from a particular device.

Getting HTTP 401 Error calling MS CRM 365 USING SOAP UI

I am trying to call MSCRM 365 web services using SOAPUI, this is what i have done so far
Downloaded Organization WSDL from my cRM instance
Uploaded in SOAPUI
Added three header parameters - Content-Type, SOAPAction and Accept
Added Username and Password in Request Properties
Whenever I send a request to MSCRM, I get "HTTP ERROR 401 - Unauthorized: Access is denied"
Anyone have any ideas?
Thanks,
Nitesh
Since this is Dynamics 365 it does not authenticate using Username / Password. Instead you will need to use OAuth as shown in the link
https://msdn.microsoft.com/en-us/library/gg327838.aspx
// TODO Substitute your correct CRM root service address,
string resource = "https://mydomain.crm.dynamics.com";
// TODO Substitute your app registration values that can be obtained after you
// register the app in Active Directory on the Microsoft Azure portal.
string clientId = "e5cf0024-a66a-4f16-85ce-99ba97a24bb2";
string redirectUrl = "http://localhost/SdkSample";
// Authenticate the registered application with Azure Active Directory.
AuthenticationContext authContext =
new AuthenticationContext("https://login.windows.net/common", false);
AuthenticationResult result = authContext.AcquireToken(resource, clientId, new
Uri(redirectUrl));
Use the access token in message requests:
using (HttpClient httpClient = new HttpClient())
{
httpClient.Timeout = new TimeSpan(0, 2, 0); // 2 minutes
httpClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", result.AccessToken);
Another options would be to shift from Xrm.Client to Xrm.Tools.Connection. See the example in this site.
https://msdn.microsoft.com/en-us/library/jj602970.aspx

why NotFound error occur in REST services with windows Phone app?

i tried to connect REST web servie from windows phone 8 application.
it was working proberly for weeks but after no change in it I get this generic error :
System.Net.WebException: The remote server returned an error:
NotFound.
i tried to test it by online REST Clients and services works properly
i tried to handle Exception and parse it as webException by this code :
var we = ex.InnerException as WebException;
if (we != null)
{
var resp = we.Response as HttpWebResponse;
response.StatusCode = resp.StatusCode;
and i get no more information and final response code is : "NotFound"
any one have any idea about what may cause this error?
there is already a trusted Certificate implemented on the server . the one who has the server suggested to have a DNS entry for the server, this entry should be at the customer DNS or in the phone hosts file .that what i done and worked for awhile but now it doesn't work however i checked that there is no thing changed
this is sample for Get Request it works proberly on Windwos Store apps :
async Task<object> GetHttps(string uri, string parRequest, Type returnType, params string[] parameters)
{
try
{
string strRequest = ConstructRequest(parRequest, parameters);
string encodedRequest = HttpUtility.UrlEncode(strRequest);
string requestURL = BackEndURL + uri + encodedRequest;
HttpWebRequest request = HttpWebRequest.Create(new Uri(requestURL, UriKind.Absolute)) as HttpWebRequest;
request.Headers["applicationName"] = AppName;
request.Headers["applicationPassword"] = AppPassword;
if (AppVersion > 1)
request.Headers["applicationVersion"] = AppVersion.ToString();
request.Method = "GET";
request.CookieContainer = cookieContainer;
var factory = new TaskFactory();
var getResponseTask = factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null);
HttpWebResponse response = await getResponseTask as HttpWebResponse;
// string s = response.GetResponseStream().ToString();
if (response.StatusCode == HttpStatusCode.OK)
{
XmlSerializer serializer = new XmlSerializer(returnType);
object obj = serializer.Deserialize(response.GetResponseStream());
return obj;
}
else
{
var Instance = Activator.CreateInstance(returnType);
(Instance as ResponseBase).NetworkError = true;
(Instance as ResponseBase).StatusCode = response.StatusCode;
return Instance;
}
}
catch (Exception ex)
{
return HandleException(ex, returnType);
}
}
i tried to monitor connections from Emulator and i found this error in connection :
**
Authentication failed because the remote party has closed the
transport stream.
**
You saw the client implement a server side certificate in the service. Did you have that certificate installed on the phone? That can be the cause of the NotFound error. Please, can you try to navigate to the service in the phone or emulator internet explorer prior to testing the app? If you do that, you can see the service working in the emulator/phone internet explorer? Maybe at that point internet explorer ask you about installing the certificate and then you can open your app, and it works.
Also remember if you are testing this in the emulator, every time you close it, the state is lost so you need to repeat the operation of installing the certificate again.
Hope this helps.
If you plan to use SSL in production in general public application (not company-distribution app), you need to ensure your certificate has one of the following root authorities:
SSL root certificates for Windows Phone OS 7.1.
When we had same issue, we purchased SSL certificate from one of those providers and after installing it on server we were able to make HTTPS requests to our services with no problem.
If you have company-distribution app, you can use any certificate from company's Root CA.

Email clients for Dynamics AX

I am wondering how the process of sending email is working between Dynamics Ax client and Email client that is set for the server as default email client.
First of all can Dynamics Ax use alternative email clients (not outlook) for sending emails and second of all is Dynamics Ax sending whole configuration to the client, or client has to be configured by itself.
Right now I am experiencing unknown error while trying to send email using Windows Live Mail.
Dynamics AX uses MAPI for client mail.
You can use the SysINetMail::sendEMail method to send a simple mail using this.
If you mail in batch another option is to use SMTP mail using SysEmailTable::sendMail.
This requires the use of mail templates.
I know this is an old question but if someone else needs it...
I am using this on a Dynamics AX 2009 and it works like a charm :)
server static boolean sendEmail(EmplId _fromEmplId, EmplId _toEmplId, str _subject, str message, EmailPriority _priority = EmailPriority::Normal)
{
boolean ok = true;
SysEmailBatch emailBatch;
EmplTable fromEmplTable;
EmplTable toEmplTable;
Email fromEmail;
Email toEmail;
;
changecompany( -- TO YOUR MASTER COMPANY --)
{
fromEmplTable = EmplTable::find(_fromEmplId);
toEmplTable = EmplTable::find(_toEmplId);
fromEmail = fromEmplTable.email();
toEmail = toEmplTable.email();
if (! fromEmail)
{
ok = checkFailed(strfmt("no email set up for %1", _fromEmplId));
}
if (! toEmail)
{
ok = checkFailed(strfmt("no email set up for %1", _toEmplId));
}
if (ok)
{
emailBatch = SysEmailBatch::construct();
emailBatch.parmSendername(fromEmplTable.name());
emailBatch.parmSenderAddr(fromEmplTable.email());
emailBatch.parmEmailAddr(toEmplTable.email());
emailBatch.parmPriority(_priority);
emailBatch.parmSubject(_subject);
emailBatch.parmMessageBody(_message);
emailBatch.run();
}
}
return ok;
}
Using SysOutgoingEmailTable and SysOutgoingEmailData you can send email to recipient of any domain and attach files too.
you have following fields:
outgoingEmailTable.EmailItemId
outgoingEmailTable.IsSystemEmail
outgoingEmailTable.Sender
outgoingEmailTable.SenderName
outgoingEmailTable.Recipient
outgoingEmailTable.Subject
outgoingEmailTable.Priority
outgoingEmailTable.WithRetries
outgoingEmailTable.RetryNum
outgoingEmailTable.UserId
outgoingEmailTable.Status
outgoingEmailTable.Message
outgoingEmailTable.TemplateId
outgoingEmailTable.LatestStatusChangeDateTime
outgoingEmailData.EmailItemId
outgoingEmailData.FileName
outgoingEmailData.EmailDataType
outgoingEmailData.FileExtension
insert respective email detail in these tables and you are good to go. Further if it gives permission error do add permission set with
CodeAccessPermission::assertMultiple .