DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Implementing API Design First in .NET for Efficient Development, Testing, and CI/CD
  • Build a Simple REST API Using Python Flask and SQLite (With Tests)
  • How to Create a Successful API Ecosystem
  • MCP Servers: The Technical Debt That Is Coming

Trending

  • Manual Sharding in PostgreSQL: A Step-by-Step Implementation Guide
  • Endpoint Security Controls: Designing a Secure Endpoint Architecture, Part 2
  • MySQL to PostgreSQL Database Migration: A Practical Case Study
  • AWS to Azure Migration: A Cloudy Journey of Challenges and Triumphs
  1. DZone
  2. Data Engineering
  3. Databases
  4. How To Send an Email With an Attachment Using PowerShell and SendGrid API

How To Send an Email With an Attachment Using PowerShell and SendGrid API

Sending email from PowerShell and SendGrid is the good option, I will explain you how to send an email with an attachement using SendGrid API instantly

By 
Ganesh Hegde user avatar
Ganesh Hegde
DZone Core CORE ·
Sep. 21, 20 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
21.0K Views

Join the DZone community and get the full member experience.

Join For Free

In this article let us discuss Sending email with attachment using Powershell and Send Grid. This includes the below steps (Also Available Github)

Advantages:

  • This can be used to send emails in Azure DevOps CI/CD Pipeline.
  • One of the important area is once your test is executed if you want to Send Test Report to respective stakeholders this will be very useful.
  • This will also answer the question of “How to send Email in Azure DevOps CI/CD Pipeline” 

Pre-Requisite: You need to have SendGrid Account (If you don’t have one create a Free Account)

Step 1: Register Sender in Send Grid
Step 2: Generate Send Grid API Key
Step 3: Create a Powershell function to send an email with attachment using SendGrid API
Step 4: Call the function using Powershell

Register Sender in SendGrid

Login to SendGrid account with your username and password 

(Note: If you do not have a SendGrid account create one using SendGrid SignUp)
Navigate to Settings > Sender Authentication


Click on Verify Single Sender



In a Create Sender Form, Enter all the mandatory details and Click on Create


Why do we need to add the Sender?

  1. Adding and verification of the sender is a must in SendGrid for security reasons.
  2. Without adding the sender, you will not be able to send the email to any person.
  3. The added sender email is used as From address in SendGrid API post request.
  4. Without adding the sender and verifying the sender, SendGrid will not allow you to send any emails.
  5. Important! Once you add the Sender, You will get an email to verify the Sender, you need to click on the Verify Sender link to complete the process of adding the sender.

Generating API Key in SendGrid

API Key is very important and mandatory if you are using SendGrid API to Send Emails

In order to Generate API Key, Go to Settings > Click on API Keys


Now, Click on Create API Key


Enter Your API Key Name, Choose Access and Click on Create and View

Once everything is done, You will see API Key

Important!: Copy the API Key and save Somewhere, If you lose this API key you can’t get it back.


Now we have successfully added the sender and generated the API key.

Next, We need to create a Powershell script to Call the API and Send an Email.

Powershell Script to Sending email with Attachment using SendGrid

In order to Send SendGrid Email, We need To Address, From Address, Subject, Body, APIToken, FileName, and FilePath and AttachementType.

Create a function with parameters

PowerShell
 




xxxxxxxxxx
1
20


 
1
Function SendGridMailWithAttachment {
2
    param (
3
        [cmdletbinding()]
4
        [parameter()]
5
        [string]$ToAddress,
6
        [parameter()]
7
        [string]$FromAddress,
8
        [parameter()]
9
        [string]$Subject,
10
        [parameter()]
11
        [string]$Body,
12
        [parameter()]
13
        [string]$APIKey,
14
        [parameter()]
15
        [string]$FileName,
16
        [parameter()]
17
        [string]$FilePathWithName,
18
        [parameter()]
19
        [string]$AttachementType
20
   )


$ToAddress: This can be any address basically it is a recipient.

$FromAddress: This must be verified address (We have added in Step 2).

$Subject: Any string this will be shown as the subject line in the inbox

$Body : Body text if you want to write anything example “Please find attachment”

$APIKey: This is your API Key which is generated in the above step.

$FileName: Important! This can be any string. Specify file with extension, not File path
Note: This filename will be shown when the user receives the email.
Example: I am attaching 1.html but $FileName the value I am giving is SampleFile.html. So in this case even though you are attaching 1.html for the user it will be shown as SampleFile.html
Example : $FileName: myAttachement.html (Do not mention any path)

$FilePathWithName: This is the original File we want to add it as an attachment. This file will be converted to base64 attachment
Example: D://1.html

$AttachementType: This is the MIME type for attachment Refer: Mime Attachment Types.
Example: text/html (for Text or HTML file as an attachement)

Create a function body

Send Grid won’t allow you to send plain files as an attachment through SendGrid API. So In order to send any file as an attachment you need to create that into base64 format First.

Let us consider, We are sending the 1.html file as an attachment to SendGrid.

Using PowerShell we can covert .html file into base64 format.

PowerShell
 




xxxxxxxxxx
1


 
1
$FileContent = get-content $FilePathWithName
2
$ConvertToBytes = [System.Text.Encoding]::UTF8.GetBytes($FileContent)
3
$EncodedFile = [System.Convert]::ToBase64String($ConvertToBytes)


In the above, the file is converted into base64 format and stored in the variable $EncodedFile.

Create SendGrid JSON Body

We need to create a send grid body object. Which will have information such as, to address, from address, body text, attachment, etc.

PowerShell
 




xxxxxxxxxx
1
27


 
1
# Body with attachement for SendGrid
2
    $SendGridBody = @{
3
        "personalizations" = @(
4
            @{
5
              "to"= @(
6
                      @{
7
                          "email" = $ToAddress
8
                       }
9
                 )              "subject" = $Subject
10
            }
11
        )      "content"= @(
12
                             @{
13
                                "type" = "text/html"
14
                                 "value" = $Body
15
                               }
16
                 ) "from"  = @{
17
                            "email" = $FromAddress
18
                           
19
                   "attachments" = @(
20
                                    @{
21
                                        "content"=$EncodedFile
22
                                        "filename"=$FileName
23
                                        "type"= $AttachementType
24
                                        "disposition"="attachment"
25
                                     }
26
                 )
27
}$BodyJson = $SendGridBody | ConvertTo-Json -Depth 4


Create header for Sendgrid Email API

We are going to pass the API key in the header.

PowerShell
 




xxxxxxxxxx
1


 
1
#Header for SendGrid API
2
$Header = @{
3
          "authorization" = "Bearer $APIKey"
4
}


Invoke SendGrid API in your function 

PowerShell
 




xxxxxxxxxx
1


 
1
#Send the email through SendGrid API
2
    $Parameters = @{
3
        Method      = "POST"
4
        Uri         = "https://api.sendgrid.com/v3/mail/send"
5
        Headers     = $Header
6
        ContentType = "application/json"
7
        Body        = $BodyJson
8
    }
9
    Invoke-RestMethod @Parameters


Putting Everything Together. The Final Powershell Script

PowerShell
 




xxxxxxxxxx
1
79


 
1
Function SendGridMailWithAttachment {
2
    param (
3
        [cmdletbinding()]
4
        [parameter()]
5
        [string]$ToAddress,
6
        [parameter()]
7
        [string]$FromAddress,
8
        [parameter()]
9
        [string]$Subject,
10
        [parameter()]
11
        [string]$Body,
12
        [parameter()]
13
        [string]$APIKey,
14
        [parameter()]
15
        [string]$FileName,
16
        [parameter()]
17
        [string]$FileNameWithFilePath,
18
        [parameter()]
19
        [string]$AttachementType
20
    )
21
 
          
22
    #Convert File to Base64
23
    $FileContent = get-content $FileNameWithFilePath
24
    $ConvertToBytes = [System.Text.Encoding]::UTF8.GetBytes($FileContent)
25
    $EncodedFile = [System.Convert]::ToBase64String($ConvertToBytes)
26
 
          
27
    # Body with attachement for SendGrid
28
    $SendGridBody = @{
29
        "personalizations" = @(
30
            @{
31
                "to"= @(
32
                              @{
33
                                   "email" = $ToAddress
34
                               }
35
                 )
36
 
          
37
                "subject" = $Subject
38
            }
39
        )
40
 
          
41
                "content"= @(
42
                              @{
43
                                    "type" = "text/html"
44
                                    "value" = $Body
45
                               }
46
                 )
47
 
          
48
                "from"  = @{
49
                            "email" = $FromAddress
50
                           }
51
 
          
52
                "attachments" = @(
53
                                    @{
54
                                        "content"=$EncodedFile
55
                                        "filename"=$FileName
56
                                        "type"= $AttachementType
57
                                        "disposition"="attachment"
58
                                     }
59
               )
60
}
61
 
          
62
    $BodyJson = $SendGridBody | ConvertTo-Json -Depth 4
63
 
          
64
 
          
65
    #Header for SendGrid API
66
    $Header = @{
67
        "authorization" = "Bearer $APIKey"
68
    }
69
 
          
70
    #Send the email through SendGrid API
71
    $Parameters = @{
72
        Method      = "POST"
73
        Uri         = "https://api.sendgrid.com/v3/mail/send"
74
        Headers     = $Header
75
        ContentType = "application/json"
76
        Body        = $BodyJson
77
    }
78
    Invoke-RestMethod @Parameters
79
}


We have created Function Powershell Script which will Send the attachment but hold on we have not called this Function this. 

Call the above Function with Parameters.

PowerShell
 




xxxxxxxxxx
1
11


 
1
$Parameters = @{
2
    ToAddress   = "example@example.com"
3
    FromAddress = "validatedemail@example.com"
4
    Subject     = "Sending Email Using SendGrid and Powershell Script"
5
    Body        = "Please find the attachement."
6
    APIKey       = "SG.JrMF8FNFSBShqPo_SpfvMoasfasfasasdfaj"
7
    FileName ="SampleAttachment.html"
8
    FileNameWithFilePath = "d://1.html"
9
    AttachementType ="text/html"
10
}
11
SendGridMailWithAttachment @Parameters


Congrats! you have successfully sent an email.

Say how this article helped by mentioning on LinkedIn https://in.linkedin.com/in/ganeshsirsi


API PowerShell

Opinions expressed by DZone contributors are their own.

Related

  • Implementing API Design First in .NET for Efficient Development, Testing, and CI/CD
  • Build a Simple REST API Using Python Flask and SQLite (With Tests)
  • How to Create a Successful API Ecosystem
  • MCP Servers: The Technical Debt That Is Coming

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!