We will deprecate this version on February 10, 2025. To access all the latest features and upcoming developments, please see our v3 API. For assistance with transitioning, refer to our migration guide.
We recommend using SendGrid Perl, our client library, available on GitHub, with full documentation.
1# Using SendGrid's Perl Library2# https://github.com/sendgrid/sendgrid-perl3use Mail::SendGrid;4use Mail::SendGrid::Transport::REST;56my $sendgrid = Mail::SendGrid->new(7from => "test@sendgrid.com",8to => "example@example.com",9subject => "Sending with SendGrid is Fun",10html => "and easy to do anywhere, even with Perl"11);1213Mail::SendGrid::Transport::REST->new( username => $api_user, api_key => $api_key );
If you choose not to use SendGrid's client library you may use Perl's generic SMTP library.
The following code builds a MIME mail message demonstrating all the portions of the SMTP API protocol. To use this example, you will need to have the following Perl modules installed:
1# !/usr/bin/perl23use strict;4use MIME::Entity;5use Net::SMTP;67# from is your email address8# to is who you are sending your email to9# subject will be the subject line of your email10my $from = 'you@yourdomain.com';11my $to = 'example@example.com';12my $subject = 'Example Perl Email';1314# Create the MIME message that will be sent. Check out MIME::Entity on CPAN for more details15my $mime = MIME::Entity->build(Type => 'multipart/alternative',16Encoding => '-SUGGEST',17From => $from,18To => $to,19Subject => $subject20);21# Create the body of the message (a plain-text and an HTML version).22# text is your plain-text email23# html is your html version of the email24# if the receiver is able to view html emails then only the html25# email will be displayed26my $text = "Hi!\nHow are you?\n";27my $html = <<EOM;28<html>29<head></head>30<body>31<p>Hi!32How are you?33</p>34</body>35</html>36EOM3738# attach the body of the email39$mime->attach(Type => 'text/plain',40Encoding =>'-SUGGEST',41Data => $text);4243$mime->attach(Type => 'text/html',44Encoding =>'-SUGGEST',45Data => $html);4647# attach a file48my $my_file_txt = 'example.txt';4950$mime->attach ( Path => $my_file_txt,51Type => 'text/txt',52Encoding => 'base64'53) or die "Error adding !\n";5455# Login credentials56my $username = 'example@example.com';57my $api_key = "your_api_key";5859# Open a connection to the SendGrid mail server60my $smtp = Net::SMTP->new('smtp.sendgrid.net',61Port=> 587,62Timeout => 20,63Hello => "yourdomain.com");6465# Authenticate66$smtp->auth($username, $api_key);6768# Send the rest of the SMTP stuff to the server69$smtp->mail($from);70$smtp->to($to);71$smtp->data($mime->stringify);72$smtp->quit();