How do I add a custom mail header using the Office365 Preview API - api

I can't find anything in the preview API or the Microsoft.Office365.Exchange namespace to let me create a custom header or get the existing headers. Here's my code create the email and the recipients.
//Create the new Message with the Office365 API and save it to the Drafts folder
var client = await EnsureClientCreated();
var o365Message = new Microsoft.Office365.Exchange.Message();
string subject = "Test subject";
o365Message.Subject = subject;
o365Message.Body = new ItemBody() { Content = "Test", ContentType = BodyType.Text };
messageModel.Subject = subject;
var recip = new Recipient();
recip.Address = "test#test.com";
o365Message.ToRecipients.Add(recip);
await client.Me.Drafts.Messages.AddMessageAsync(o365Message, false);
Thx,

This isn't available right now from the service. I see nothing about mail headers in the metadata document. Please use UserVoice to request this feature.

Related

'Restclient' does not contain a 'BaseUrl' Error

I am working on Asp.net core project. trying to send mail using mailgun. used mailgun C# code given in https://documentation.mailgun.com/en/latest/user_manual.html#sending-via-api
But getting an error "RestClient" does not contain a "BaseUrl" error.
I saw your Comment Code, I think You have to Change this to get the Output.
var client = new RestClient();
client.BaseUrl = "https://api.mailgun.net/v3";
client.Authenticator = new HttpBasicAuthenticator("api", "YOUR_API_KEY");
var request = new RestRequest();
request.Resource = "/address/validate";
request.AddParameter("address", "address#domain.com");
//Change Resource and AddParameter as per need
var response = client.Execute(request);
dynamic content = Json.Decode(response.Content);
var client = new RestClient(new Uri("yourbaseurl"));

How to send email from any one email using Microsoft Graph

I am using microsoft graph to send email. This email I want to send from any email that exists in the Active directory.
I already have get the permission on Mail.Send and have admin consent on Azure.So all set on the Azure level for access and permission.
Now when come to code. I have searched for but I am not able to figure out how to call the Microsoft graph api to send the email. Below is the code that I have been finding when I am doing search. How I can replace the below code to send the email to anyone from anyone in Azure AD to anyone in Azure AD. Also the code for send email 'Send AS'.
await graphClient.Me.Messages
.Request()
.AddAsync(message);
The intention is the signed in user will not send email from his email
address, the email notification will be asthmatically sent by someone
else name to someone.
Then I think you wanna provide a sending email to your users, users can choose who received the email, but all the email should be sent be a specific account, such as admin#xxx.onmicrosoft.com, then you should know something about the sending email api.
As #user2250152 mentioned, await graphClient.Users["userId"], here the userId means who send the email, as your requirement is sending all emails from one specific email address, it should hardcode as admin#xxx.onmicrosoft.com.
The next is how to send the email, calling ms graph api should offer an access token, as your requirement is sending email by the application but not every user, so I'm afraid the client credential flow is a better choice so that when the scenario comes to sending email from several specific email addresses, you don't need to change the flow then. Now you need to require your tenant admin to add Mail.Send Application api permission in azure ad to use this kind of flow.
And here's the code:
using Azure.Identity;
using Microsoft.Graph;
var mesg = new Message
{
Subject = "Meet for lunch?",
Body = new ItemBody
{
ContentType = BodyType.Text,
Content = "The new cafeteria is open."
},
ToRecipients = new List<Recipient>
{
new Recipient
{
EmailAddress = new EmailAddress
{
//who will receive the email
Address = "xxx#gmail.com"
}
}
},
Attachments = new MessageAttachmentsCollectionPage()
};
var scopes = new[] { "https://graph.microsoft.com/.default" };
var tenantId = "your_tenant_name.onmicrosoft.com";
var clientId = "azure_ad_app_client_id";
var clientSecret = "client_secret_for_the_azuread_app";
var clientSecretCredential = new ClientSecretCredential(
tenantId, clientId, clientSecret);
var graphClient = new GraphServiceClient(clientSecretCredential, scopes);
await graphClient.Users["user_id_which_you_wanna_used_for_sending_email"].SendMail(mesg, false).Request().PostAsync();
You can send mail from other user this way.
var message = new Message
{
Subject = "Subject",
Body = new ItemBody
{
ContentType = BodyType.Text,
Content = "Content"
},
ToRecipients = new List<Recipient>()
{
new Recipient
{
EmailAddress = new EmailAddress
{
Address = "john.doe#contoso.onmicrosoft.com"
}
}
}
};
var saveToSentItems = false;
await graphClient.Users["userId"]
.SendMail(message,saveToSentItems)
.Request()
.PostAsync();
userId is the unique identifier for the user. Instead of userId you can use userPrincipalName. The UPN is an Internet-style login name for the user based on the Internet standard RFC 822. By convention, this should map to the user's email name.
Resources:
Send mail
User resource

How to get microsoft account profile photo after login with application in mvc

With the help of claimprincipal, I'm able to get the details of signedin user as below but its not giving any pic related information as google does:
https://apis.live.net/v5.0/{USER_ID}/picture?type=large
which says The URL contains the path '{user_id}', which isn't supported.
Even tried
https://graph.microsoft.com/v1.0/me/photo/$value
which is asking for access token, but I am not sure what have to be passed
string userName = ClaimsPrincipal.Current.FindFirst("name").Value;
string userEmail = ClaimsPrincipal.Current.FindFirst(ClaimTypes.Email).Value;
string userId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
Wanted an image which was added in any outlook account
For Image to show.. We have to use beared token and have to convert the image into memory stream and then have to used it.. I have done it in below ways. Hope this help ...
var client = new RestClient("https://login.microsoftonline.com/common/oauth2/token");
var request = new RestRequest(Method.POST);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddParameter("application/x-www-form-urlencoded", $"code={code}&client_id={OutClientId}&client_secret={SecretKey}&redirect_uri={OutRedirectUrl}&grant_type=authorization_code", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Token jsonContent = JsonConvert.DeserializeObject<Token>(response.Content);
var Token = jsonContent.AccessToken;
var TokenType = jsonContent.TokenType;
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Token);
HttpResponseMessage response1 = await httpClient.GetAsync("https://graph.microsoft.com/v1.0/me/photos/96x96/$value");
if (response1.StatusCode == HttpStatusCode.OK)
{
using (Stream responseStream = await response1.Content.ReadAsStreamAsync())
{
MemoryStream ms = new MemoryStream();
responseStream.CopyTo(ms);
byte[] buffer = ms.ToArray();
string result = Convert.ToBase64String(buffer);
HttpContext.Session[AppConstants.UserImage] = String.Format("data:image/gif;base64,{0}", result);
responseStream.Close();
}
}
Is there any reason you are using the live.net apis? Instead of the Microsoft Graph APIs? Microsoft Graph APIs are the future for all user data within Microsoft 365 consumer and commercial accounts.
You can get the Users photo very easily as described here https://learn.microsoft.com/en-us/graph/api/profilephoto-get?view=graph-rest-1.0
GET /me/photo/$value
As you are using ASP.NET MVC, there is an SDK you can use that makes this very easy too.
https://learn.microsoft.com/en-us/graph/sdks/sdks-overview?context=graph%2Fapi%2F1.0&view=graph-rest-1.0

Smartsheet API Email Recipients

Apologies for the basic question, but how do I add multiple recipients (email addresses) to an email object with the Smartsheet VB (uses C#) SDK?
Documentation here but cant see how to add multiples:
http://smartsheet-platform.github.io/api-docs/?csharp#email-object
The following code example shows how to specify two recipients, construct an email object, and execute the SendSheet operation using that email object. The same technique for specifying recipients and constructing the email object can be applied to other Send operations (e.g., SendReport, SendRow, etc.).
// Specify recipients
Recipient[] recipients = new Recipient[] {
new Recipient { Email = "john.doe#smartsheet.com" },
new Recipient { Email = "jane.doe#smartsheet.com" }
};
// Configure email
SheetEmail sheetEmail = new SheetEmail {
SendTo = recipients,
Subject = "Check this sheet out!",
Message = "Here's the sheet I mentioned in our meeting.",
CcMe = false,
Format = SheetEmailFormat.PDF,
FormatDetails = new FormatDetails { PaperSize = PaperSize.A4 }
};
// Send sheet via email
smartsheet.SheetResources.SendSheet(SHEET_ID, sheetEmail);

Attaching an Image to Work item in Visual Studio Team Services (was Visual Studio Online)

I'm sending an attachment through the Visual Studio Team Services API and it all look like its fine, until I look at the attachment on the work item.
The attachment should be a picture, but it a little black box with a white cross.
Has anyone had this issue and does anyone know what I've done wrong?
I get the image and convert it to a 64 Base string
FileInfo info = new FileInfo(attachment.Path);
byte[] bytes = File.ReadAllBytes(info.FullName);
String file = Convert.ToBase64String(bytes);
Then I send it to the API. This returns a message saying its been successful.
using (System.Net.Http.HttpClient client = new System.Net.Http.HttpClient())
{
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(getConnectionDetails())));
using (System.Net.Http.HttpResponseMessage response = client.PostAsync(SetURL(url),
new StringContent(binaryString,Encoding.UTF8,"application/json")).Result)
{
response.EnsureSuccessStatusCode();
responseString = await response.Content.ReadAsStringAsync();
}
}
I think its something small, that I'm missing!
This is the link to the document, I have used.
API document
Try it this way:
...
string uri = "https://xxxxxx.visualstudio.com/_apis/wit/attachments?fileName=test.jpg&api-version=1.0";
string filepath = "C:\\images\\test.jpg";
FileStream files = new FileStream(filepath,FileMode.Open);
StreamContent streamcontent = new StreamContent(files);
...
HttpResponseMessage response = hc.PostAsync(uri, streamcontent).Result;
...