Send Email with .NET API call. Samples / Examples required.

  • 1
  • Question
  • Updated 2 days ago
Are there any examples / samples of how to send an email via the API in C# or VB.net? I have downloaded the available sample for uploading a file but cant find one for emails. 
Photo of Chris

Chris

  • 17 Posts
  • 2 Reply Likes

Posted 1 year ago

  • 1
Photo of Andy Berryman

Andy Berryman, Software Engineer

  • 19 Posts
  • 5 Reply Likes
Are you referring to the ability to send access to an uploaded file via the ShareFile Shares functionality?

https://api.sharefile.com/rest/docs/resource.aspx?name=Shares

- Andy
Photo of Chris

Chris

  • 17 Posts
  • 2 Reply Likes
Hi,
No, I am referring to the ability to send encrypted emails via an API.

https://api.sharefile.com/rest/docs/resource.aspx?name=EncryptedEmails

I wondered if anyone had any examples.
Photo of Andy Berryman

Andy Berryman, Software Engineer

  • 19 Posts
  • 5 Reply Likes
Ok ... Let me see if I can find one in something we have already.  If not ... We'll create one for you.

- Andy
Photo of Chris

Chris

  • 17 Posts
  • 2 Reply Likes
Brilliant thanks
Photo of Andy Berryman

Andy Berryman, Software Engineer

  • 19 Posts
  • 5 Reply Likes
Sorta quickly threw this thing together ... It's shown as using the .NET SDK ... But should show you the flow that you need ...

// Assume you have your ShareFile Client initialized and ready to make calls
var sfClient = ...;

// First you need to have a local file that contains the desired Message Body for the Email
var myMsgBodyFile = @"C:\temp\EmailBody.txt";

// Next you need to upload those contents into ShareFile so that you can reference them for the Email
var parentFolderToUploadToUri = "fill me in";
var uploadedFileId = null;
using (var readStream = new FileInfo(myMsgBodyFile).OpenRead())
{
	var uploadSpec = new UploadSpecificationRequest
	{
		FileName = readStream.Name,
		FileSize = readStream.Length,
		Parent = parentFolderToUploadToUri,
		Method = UploadMethod.Standard
	};
	
	var fileUploader = sfClient.GetAsyncFileUploader(uploadSpec, readStream);
	fileUploader.Config.HttpTimeout = sfClient.Configuration.HttpTimeout;
	
	var uploadResponse = fileUploader.UploadAsync().Result;
	uploadedFileId = uploadResponse[0].Id;
}

// Next create your EncryptedEmail entity
var toRecipients = new List
{
	new Principal
	{
		Name = "fill me in",
		Email = "fill@me.in"
	}
};

var emailParams = new EncryptedEmailCreateParams
{
	Subject = "fill me in",
	ToRecipients = toRecipients,
	RequireLogin = true,
	ExpirationDays = 3
};

var encryptedEmail = sfClient.EncryptedEmails.Create(emailParams).Execute();

// Send the Email
var sendParams = new EncryptedEmailSendParams
{
	Message = new Item() { Id = uploadedFileId },
};
sfClient.EncryptedEmails.Send(encryptedEmail.url, sendParams).Execute();
Photo of Pratik Somanagoudar

Pratik Somanagoudar, Software Engineer

  • 24 Posts
  • 2 Reply Likes
Hi Jeremy

Sorry for the delayed response. I was able to figure out the problem here. You are using uploadid instead of the the fileId for the file uploaded in the message, hence the system is not able to find the file with the message. I have an example code for you to try, Let me know if this works : 

Imports System.Web
Imports System.Net
Imports System.IO

Imports Newtonsoft.Json.Linq
Imports Newtonsoft.Json
Imports ShareFile.Api.Client
Imports ShareFile.Api.Client.Models
Imports System.Text
Imports ShareFile.Api.Client.Transfers
Module Module1

    Class OAuth2Token
        Public Property AccessToken As String
        Public Property RefreshToken As String
        Public Property TokenType As String
        Public Property Appcp As String
        Public Property Apicp As String
        Public Property Subdomain As String
        Public Property ExpiresIn As Integer

        Sub New(ByVal json As JObject)
            If json IsNot Nothing Then
                AccessToken = json.GetValue("access_token")
                RefreshToken = json.GetValue("refresh_token")
                TokenType = json.GetValue("token_type")
                Appcp = json.GetValue("appcp")
                Apicp = json.GetValue("apicp")
                Subdomain = json.GetValue("subdomain")
                ExpiresIn = json.GetValue("expires_in")
            End If
        End Sub
    End Class

    ''' <summary>
    ''' Authenticate via username/password
    ''' </summary>
    ''' <param name="hostname">hostname like "myaccount.sharefile.com"</param>
    ''' <param name="clientId">my client id</param>
    ''' <param name="clientSecret">my client secret</param>
    ''' <param name="username">my@user.name</param>
    ''' <param name="password">mypassword</param>
    ''' <returns></returns>
    Function Authenticate(ByVal hostname As String, ByVal clientId As String, ByVal clientSecret As String, ByVal username As String, ByVal password As String)
        Dim uri As String = String.Format("https://{0}/oauth/token";, hostname)
        Console.WriteLine(uri)

        Dim parameters As Dictionary(Of String, Object) = New Dictionary(Of String, Object)
        parameters.Add("grant_type", "password")
        parameters.Add("client_id", clientId)
        parameters.Add("client_secret", clientSecret)
        parameters.Add("username", username)
        parameters.Add("password", password)

        Dim bodyParameters As ArrayList = New ArrayList()
        For Each kv As KeyValuePair(Of String, Object) In parameters
            bodyParameters.Add(String.Format("{0}={1}", HttpUtility.UrlEncode(kv.Key), HttpUtility.UrlEncode(kv.Value.ToString())))
        Next

        Dim requestBody As String = String.Join("&", bodyParameters.ToArray())

        Dim request As HttpWebRequest = WebRequest.CreateHttp(uri)
        request.Method = "POST"
        request.ContentType = "application/x-www-form-urlencoded"
        Using writer As New StreamWriter(request.GetRequestStream())
            writer.Write(requestBody)
        End Using

        Dim response As HttpWebResponse = request.GetResponse()
        Console.WriteLine(response.StatusCode)
        Dim token As JObject = Nothing
        Using reader As New StreamReader(response.GetResponseStream())
            Dim body As String = reader.ReadToEnd()
            token = JObject.Parse(body)
        End Using
        Return New OAuth2Token(token)
    End Function

    Sub AddAuthenticationHeader(ByRef request As HttpWebRequest, ByVal token As OAuth2Token)
        request.Headers.Add(String.Format("Authorization: Bearer {0}", token.AccessToken))
    End Sub


    Sub Main()
        Dim hostname As String = "domain.sf-api.com"
        Dim username As String = "email"
        Dim password As String = "password"
        Dim clientId As String = "clientId"
        Dim clientSecret As String = "clientSecret"
        Dim token As OAuth2Token = Authenticate(hostname, clientId, clientSecret, username, password)

        Dim apiUrl As String = $"https://{hostname}/sf/v3";
        Dim objShareFileClient As IShareFileClient = New ShareFileClient(apiUrl)
        objShareFileClient.AddOAuthCredentials(New Uri(apiUrl), token.AccessToken)

        Dim principal As Principal = New Principal With {
            .Email = "Email@gmail.com"
        }

        Dim toRecipients As List(Of Principal) = New List(Of Principal)()
        toRecipients.Add(principal)

        Dim EEParamsObject As EncryptedEmailCreateParams = New EncryptedEmailCreateParams With {
            .Subject = "TestSubject Final",
            .ToRecipients = toRecipients,
            .RequireLogin = False,
            .NotifyOnUse = False,
            .RequireUserInfo = True,
            .ExpirationDays = 180
            }

        Dim objEncryptedEmail As Models.EncryptedEmail = objShareFileClient.EncryptedEmails.Create(EEParamsObject).Execute

        Console.WriteLine(objEncryptedEmail.Id)

        Dim FilePathToUpload As String = "G:\\test1.txt"

        Dim fileInfo As FileInfo = New FileInfo(Path.GetFullPath(FilePathToUpload))


        Dim objUploadRequestParams As New UploadRequestParams With {
            .FileName = fileInfo.Name,
            .FileSize = fileInfo.Length,
            .Method = Models.UploadMethod.Threaded,
            .Raw = True
        }

        Dim objUploadSpecificationResponse As UploadSpecification = objShareFileClient.EncryptedEmails.Upload2(objEncryptedEmail.url, objUploadRequestParams, 1).Execute()

        If objUploadSpecificationResponse.ChunkUri IsNot Nothing Then

            Using stream = fileInfo.OpenRead()

                Dim uploadSpec As UploadSpecificationRequest = New UploadSpecificationRequest With
                {
                    .FileName = fileInfo.Name,
                    .FileSize = fileInfo.Length,
                    .Parent = objEncryptedEmail.url,
                    .Method = Models.UploadMethod.Threaded,
                    .Raw = True
                }

                Dim uploader = objShareFileClient.GetAsyncFileUploader(uploadSpec, stream)
                uploader.Config.HttpTimeout = objShareFileClient.Configuration.HttpTimeout
                Dim uploadResponse As UploadResponse = uploader.UploadAsync().GetAwaiter().GetResult()
                Dim sendParams As EncryptedEmailSendParams = New EncryptedEmailSendParams With
                {
                    .Message = New Item With {
                    .Id = uploadResponse.FirstOrDefault().Id
                    }
                }

                objShareFileClient.EncryptedEmails.Send(objEncryptedEmail.url, sendParams).Execute()
            End Using
        End If

    End Sub
End Module

Photo of Jeremy Sutka

Jeremy Sutka

  • 20 Posts
  • 1 Reply Like
I am still getting no data in the sent message.  I think it is because I am not using content that is stored in a file: Dim FilePathToUpload As String = "G:\\test1.txt"

I am instead trying to send a string as the message content.  I am not sure if I need a different uploader or stream OR if since I do not have a file, there is no file size to set to be able to send the data.
Photo of Jeremy Sutka

Jeremy Sutka

  • 20 Posts
  • 1 Reply Like
Never mind, I was able to do this making the following modifications for string p_strBody:

        Dim objBytes() As Byte = New System.Text.UTF8Encoding().GetBytes(p_strBody)

        Dim objUploadRequestParams As New Models.UploadRequestParams
        With objUploadRequestParams
            .Raw = True
            .FileName = "message.txt"
            .FileSize = 0
            .Method = Models.UploadMethod.Threaded
        End With

        Dim objUploadSpecificationResponse As Models.UploadSpecification = objShareFileClient.EncryptedEmails.Upload2(objEncryptedEmail.url, objUploadRequestParams, 1).Execute

        Dim objUploadSpecificationRequest As New Transfers.UploadSpecificationRequest
        With objUploadSpecificationRequest
            .Raw = True
            .FileName = "message.txt"
            .FileSize = objBytes.Length
            .Parent = objEncryptedEmail.url
            .Method = Models.UploadMethod.Threaded
        End With

        Dim objStream As New IO.MemoryStream
        objStream.Write(objBytes, 0, objBytes.Length)

        Dim objUploader As Transfers.Uploaders.AsyncScalingFileUploader = objShareFileClient.GetAsyncFileUploader(objUploadSpecificationRequest, objStream)

Photo of Pratik Somanagoudar

Pratik Somanagoudar, Software Engineer

  • 24 Posts
  • 2 Reply Likes
So, Did it work for you now? 
Photo of Jeremy Sutka

Jeremy Sutka

  • 20 Posts
  • 1 Reply Like
Yes, I have it successfully working now.  We will be implementing to our production environment in a couple of weeks, so fingers crossed it will work.
Photo of Chris

Chris

  • 17 Posts
  • 2 Reply Likes
Brilliant, I will give it a try.

Thank you for the quick response.

Can the message body be uploaded as HTML or does it only work if it is plain text?
Photo of Andy Berryman

Andy Berryman, Software Engineer

  • 19 Posts
  • 5 Reply Likes
Yes I believe that HTML will work.

- Andy
Photo of Chris

Chris

  • 17 Posts
  • 2 Reply Likes
Do you have a sample project with this working? I have tried using it with the supplied SDK but EncryptedEmails doesn't appear to be recognized by the samples.
Photo of Luke Skrzypek

Luke Skrzypek, Software Engineer

  • 70 Posts
  • 8 Reply Likes
Which SDK and version are you using?
I just tried with the latest C# SDK (v4.0.200), and the ShareFile client object does expose the EncryptedEmails endpoint.

ShareFile.Api.Client.ShareFileClient shareFileClient = new ShareFileClient(...);
...
shareFileClient.EncryptedEmails.Send(...);
Photo of Chris

Chris

  • 17 Posts
  • 2 Reply Likes
I was using 3.033 i believe, I have tried it with v4.0.200 but it hangs on await oauthService.PasswordGrantAsync, so I was wondering if there were any updated samples with the email functionality.
(Edited)
Photo of Luke Skrzypek

Luke Skrzypek, Software Engineer

  • 70 Posts
  • 8 Reply Likes
Responded to you on your other thread.