Mailing Through Exchange webservice (VB.NET) - web-services

Anyone here who has experience with using Exchange webservice.
I am trying to send an e-mail to myself using the webservice. This e-mail has another address as Sender, but it keeps taking my recipients e-mail address as Sender instead :s
This is my code:
Dim Message As MessageType = New MessageType()
Message.Subject = txt
Message.Body = New BodyType()
Message.Body.Value = ActiesOverzicht
Message.Sender = New SingleRecipientType
Message.Sender.Item = New EmailAddressType
Message.Sender.Item.EmailAddress = SenderEmail
Message.ToRecipients = New EmailAddressType(0) {}
Message.ToRecipients(0) = New EmailAddressType()
Message.ToRecipients(0).EmailAddress = RecipientsEmail
Message.Sensitivity = SensitivityChoicesType.Normal
this message goes into a list and is send with the following Code:
Public Sub SendMailToOperator(messageList As List(Of MessageType), esb As ExchangeServiceBinding)
' Create the CreateItem request.
Dim createEmailRequest As New CreateItemType()
' Specifiy how the e-mail will be handled.
createEmailRequest.MessageDisposition = MessageDispositionType.SendOnly
createEmailRequest.MessageDispositionSpecified = True
' Create the array of items.
createEmailRequest.Items = New NonEmptyArrayOfAllItemsType()
' Add the message to the array of items to be created.
createEmailRequest.Items.Items = messageList.ToArray()
'createEmailRequest.Items.Items(0) = Message
' Send a CreateItem request and get the CreateItem
' response.
Dim createItemResponse As CreateItemResponseType = esb.CreateItem(createEmailRequest)
End Sub
Does anyone have any Idea on how to solve this problem? Or what causes it?

AFAIK Exchange will normally always set the sender to the identity of the person logged in.
There are several ways around this, the easiest one being not using Exchange. Just send mail trough 'normal' SMTP.
If you have to use Exchange you should log in as the sender you're trying to use, or set up the permissions for the account you are trying to use as sender. The sender you're using should allow the account you use to login to send mail on it's behalf. The permissions can be changed through outlook.
There might also be a way to relax this restriction on the Exchange server, but I'm not an Exchange admin so I don't know how.

Related

Flutter HTTP request using Basic Auth + passing user and password to receive user data back

I am a newcomer, not a professional coder (so be gentle), trying to build a Flutter app that must connect to a web/server API in HTTP.
According to the doc, to make a connection a header must be used, this header uses the Basic Ath method, with login and password + a content type.
Till that point I think I have found how to do (see code snippet hereunder) but I have to send a user id and a user password to the API in order to receive back user data. And I must humbly confess that I am stuck there...
I thank you in advance for your help!
Bernard
My code (after importing dart:convert et package:http/http.dart + installed the required dependencies) :
void brol() async {
String username = 'user';
String password = 'pass';
String userpass = '$username:$password';
String basicAuth =
'Basic ' + userpass;
print(basicAuth);
Response r = await get('https://www.adresse/login.php',
headers: {'authorization': basicAuth});
}
Many Thanks in advance for your answer,
Bernard
Your credentials should be in base64. You can visit the SO post in the comment.
Your code should be look like this:
main() async {
String username = 'user';
String password = 'pass';
String basicAuth =
'Basic ' + base64Encode(utf8.encode('$username:$password'));
print(basicAuth);
Response r = await get('https://www.adresse/login.php',
headers: <String, String>{'authorization': basicAuth});
print(r.statusCode);
print(r.body);
}
See also this blog post.

Identity Server 3 Facebook Login Get Email

Identity server is implemented and working well. Google login is working and is returning several claims including email.
Facebook login is working, and my app is live and requests email permissions when a new user logs in.
The problem is that I can't get the email back from the oauth endpoint and I can't seem to find the access_token to manually request user information. All I have is a "code" returned from the facebook login endpoint.
Here's the IdentityServer setup.
var fb = new FacebookAuthenticationOptions
{
AuthenticationType = "Facebook",
SignInAsAuthenticationType = signInAsType,
AppId = ConfigurationManager.AppSettings["Facebook:AppId"],
AppSecret = ConfigurationManager.AppSettings["Facebook:AppSecret"]
};
fb.Scope.Add("email");
app.UseFacebookAuthentication(fb);
Then of course I've customized the AuthenticateLocalAsync method, but the claims I'm receiving only include name. No email claim.
Digging through the source code for identity server, I realized that there are some claims things happening to transform facebook claims, so I extended that class to debug into it and see if it was stripping out any claims, which it's not.
I also watched the http calls with fiddler, and I only see the following (apologies as code formatting doesn't work very good on urls. I tried to format the querystring params one their own lines but it didn't take)
(facebook.com)
/dialog/oauth
?response_type=code
&client_id=xxx
&redirect_uri=https%3A%2F%2Fidentity.[site].com%2Fid%2Fsignin-facebook
&scope=email
&state=xxx
(facebook.com)
/login.php
?skip_api_login=1
&api_key=xxx
&signed_next=1
&next=https%3A%2F%2Fwww.facebook.com%2Fv2.7%2Fdialog%2Foauth%3Fredirect_uri%3Dhttps%253A%252F%252Fidentity.[site].com%252Fid%252Fsignin-facebook%26state%3Dxxx%26scope%3Demail%26response_type%3Dcode%26client_id%3Dxxx%26ret%3Dlogin%26logger_id%3Dxxx&cancel_url=https%3A%2F%2Fidentity.[site].com%2Fid%2Fsignin-facebook%3Ferror%3Daccess_denied%26error_code%3D200%26error_description%3DPermissions%2Berror%26error_reason%3Duser_denied%26state%3Dxxx%23_%3D_
&display=page
&locale=en_US
&logger_id=xxx
(facebook.com)
POST /cookie/consent/?pv=1&dpr=1 HTTP/1.1
(facebook.com)
/login.php
?login_attempt=1
&next=https%3A%2F%2Fwww.facebook.com%2Fv2.7%2Fdialog%2Foauth%3Fredirect_uri%3Dhttps%253A%252F%252Fidentity.[site].com%252Fid%252Fsignin-facebook%26state%3Dxxx%26scope%3Demail%26response_type%3Dcode%26client_id%3Dxxx%26ret%3Dlogin%26logger_id%3Dxxx
&lwv=100
(facebook.com)
/v2.7/dialog/oauth
?redirect_uri=https%3A%2F%2Fidentity.[site].com%2Fid%2Fsignin-facebook
&state=xxx
&scope=email
&response_type=code
&client_id=xxx
&ret=login
&logger_id=xxx
&hash=xxx
(identity server)
/id/signin-facebook
?code=xxx
&state=xxx
I saw the code parameter on that last call and thought that maybe I could use the code there to get the access_token from the facebook API https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow
However when I tried that I get a message from the API telling me the code has already been used.
I also tried to change the UserInformationEndpoint to the FacebookAuthenticationOptions to force it to ask for the email by appending ?fields=email to the end of the default endpoint location, but that causes identity server to spit out the error "There was an error logging into the external provider. The error message is: access_denied".
I might be able to fix this all if I can change the middleware to send the request with response_type=id_token but I can't figure out how to do that or how to extract that access token when it gets returned in the first place to be able to use the Facebook C# sdk.
So I guess any help or direction at all would be awesome. I've spent countless hours researching and trying to solve the problem. All I need to do is get the email address of the logged-in user via IdentityServer3. Doesn't sound so hard and yet I'm stuck.
I finally figured this out. The answer has something to do with Mitra's comments although neither of those answers quite seemed to fit the bill, so I'm putting another one here. First, you need to request the access_token, not code (authorization code) from Facebook's Authentication endpoint. To do that, set it up like this
var fb = new FacebookAuthenticationOptions
{
AuthenticationType = "Facebook",
SignInAsAuthenticationType = signInAsType,
AppId = ConfigurationManager.AppSettings["Facebook:AppId"],
AppSecret = ConfigurationManager.AppSettings["Facebook:AppSecret"],
Provider = new FacebookAuthenticationProvider()
{
OnAuthenticated = (context) =>
{
context.Identity.AddClaim(new System.Security.Claims.Claim("urn:facebook:access_token", context.AccessToken, ClaimValueTypes.String, "Facebook"));
return Task.FromResult(0);
}
}
};
fb.Scope.Add("email");
app.UseFacebookAuthentication(fb);
Then, you need to catch the response once it's logged in. I'm using the following file from the IdentityServer3 Samples Repository, which overrides (read, provides functionality) for the methods necessary to log a user in from external sites. From this response, I'm using the C# Facebook SDK with the newly returned access_token claim in the ExternalAuthenticationContext to request the fields I need and add them to the list of claims. Then I can use that information to create/log in the user.
public override async Task AuthenticateExternalAsync(ExternalAuthenticationContext ctx)
{
var externalUser = ctx.ExternalIdentity;
var claimsList = ctx.ExternalIdentity.Claims.ToList();
if (externalUser.Provider == "Facebook")
{
var extraClaims = GetAdditionalFacebookClaims(externalUser.Claims.First(claim => claim.Type == "urn:facebook:access_token"));
claimsList.Add(new Claim("email", extraClaims.First(k => k.Key == "email").Value.ToString()));
claimsList.Add(new Claim("given_name", extraClaims.First(k => k.Key == "first_name").Value.ToString()));
claimsList.Add(new Claim("family_name", extraClaims.First(k => k.Key == "last_name").Value.ToString()));
}
if (externalUser == null)
{
throw new ArgumentNullException("externalUser");
}
var user = await userManager.FindAsync(new Microsoft.AspNet.Identity.UserLoginInfo(externalUser.Provider, externalUser.ProviderId));
if (user == null)
{
ctx.AuthenticateResult = await ProcessNewExternalAccountAsync(externalUser.Provider, externalUser.ProviderId, claimsList);
}
else
{
ctx.AuthenticateResult = await ProcessExistingExternalAccountAsync(user.Id, externalUser.Provider, externalUser.ProviderId, claimsList);
}
}
And that's it! If you have any suggestions for simplifying this process, please let me know. I was going to modify this code to do perform the call to the API from FacebookAuthenticationOptions, but the Events property no longer exists apparently.
Edit: the GetAdditionalFacebookClaims method is simply a method that creates a new FacebookClient given the access token that was pulled out and queries the Facebook API for the other user claims you need. For example, my method looks like this:
protected static JsonObject GetAdditionalFacebookClaims(Claim accessToken)
{
var fb = new FacebookClient(accessToken.Value);
return fb.Get("me", new {fields = new[] {"email", "first_name", "last_name"}}) as JsonObject;
}

Accessing Current Recipient in Sitecore 8 Email Experience Manager

How do you get the raw contact id from the ec_contact_id on the URL created by EXM?
We are using Sitecore's EXM to send emails containing links for surveys to recipients. When the recipient takes the survey we want to tie the response back to the recipient. Since EXM puts a unique Id, ec_contact_id, for the contact (encrypted) we want to use that to determine the recipient versus adding our own custom id.
We found this article, https://briancaos.wordpress.com/2015/04/27/sitecore-8-exm-get-the-email-recipient-from-a-sublayout/, and tried implementing it in the Sitecore controller that gets called when the recipient clicks on the link but the resulting recipient name comes back as empty. We don't have a "sc_item_id" value so we tried "_id" and "ec_message_id" in its place but neither value produced a valid contact Id or recipient name. We also tried looking in MongoDB with the decrypted contactId but couldn't find a match.
You could try somthing like this:
//get value of the ec_contact_id parameter for current request
string queryString = WebUtil.GetQueryString( Sitecore.Modules.EmailCampaign.GlobalSettings.AnalyticsContactIdQueryKey);
var shortID = ShortID.TryParse(queryString, out shortID);
System.Guid contactId;
// where initializationVector is System.Guid of your email message item.
using (var cryptoServiceProvider = new GuidCryptoServiceProvider(System.Text.Encoding.UTF8.GetBytes(GlobalSettings.PrivateKey), initializationVector.ToByteArray()))
{
contactId = cryptoServiceProvider.Decrypt(shortID.Guid);
}
When you create a new user in an email list, Sitecore creates a record in the xDB Mongo database. You should be able to get the email address from the users profile.
Tracker.Current.Contact.GetFacet<IContactEmailAddresses>("Emails").Entries[Tracker.Current.Contact.GetFacet<IContactEmailAddresses>("Emails").Preferred]
Tracker.Current.Contact.GetFacet<IContactEmailAddresses>("Emails").Entries["work_email"]

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 .

How to retrieve request info by request id?

When I invite my friends I get back request_ids. After that I proceed those ids to get info about users invites have been sent to and create records in my database based on user's public profile info. But when I try to get request info by request id I get error message saying "Unsupported get request" nevertheless access token is fine.
// create data object to be sent to FB API
var data = new Object();
data.method = 'apprequests';
data.message = MESSAGE_TEXT;
data.display = 'iframe';
data.access_token = ACCESS_TOKEN;
data.show_error = 'Yes';
data.title = TITLE_TEXT;
// call FB API
FB.ui(data, function(aResponse)
{
var request_ids = '';
if (aResponse && aResponse.request_ids)
request_ids = aResponse.request_ids.join(',');
if (request_ids)
{
// send request_ids string to my server for further processing
}
});
Example of such broken request id: 1930910810837. Trying to get info for it like this:
https://graph.facebook.com/1930910810837?access_token=ACCESS_TOKEN
Please help me understand what is wrong. May it be issue on Facebook side, for example, Facebook returned broken id for some reason? Thank you!!!