Last active
March 29, 2016 16:05
-
-
Save MadcapJake/05ecec7b8db16fa83b74 to your computer and use it in GitHub Desktop.
Sending emails with Net::Curl
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use NativeCall; | |
use Net::Curl::NativeCall; | |
use Email::Simple; | |
constant EmailPassword = %*ENV<P6BUG_EMAIL_PW>; | |
constant FROM = '[email protected]'; | |
constant TO = '[email protected]'; | |
constant CC = '[email protected]'; | |
constant Email = Email::Simple.new( | |
[['To', TO], ['FROM', FROM], ['CC', CC], ['Subject', 'Testing']], | |
'This is a test email!' | |
).Str; | |
with curl_easy_init() { | |
curl_easy_setopt($_, CURLOPT_USERNAME, FROM); | |
curl_easy_setopt($_, CURLOPT_PASSWORD, EmailPassword); | |
curl_easy_setopt($_, CURLOPT_URL, 'smtp://smtp.gmail.com:587'); | |
curl_easy_setopt($_, CURLOPT_USE_SSL, CURLUSESSL_ALL); | |
curl_easy_setopt($_, CURLOPT_CAINFO, 'vendor/smtp-gmail.pem'); | |
curl_easy_setopt($_, CURLOPT_MAIL_FROM, FROM); | |
my $recipients = curl_slist_append(curl_slist, TO); | |
$recipients = curl_slist_append($recipients, CC); | |
curl_easy_setopt($_, CURLOPT_MAIL_RCPT, $recipients); | |
class ReadContext is repr('CStruct') { | |
has int32 $lines_read; | |
} | |
sub memcpy(Pointer $dest, Pointer $src, size_t $n) returns Pointer is native(Str) {*} | |
sub read_callback(CArray[uint8] $buffer, size_t $size, size_t $nitems, ReadContext $ctx) | |
returns size_t is native() { | |
return 0 if $size == 0 and $nitems == 0 and $size*$nitems < 1; | |
my Str $data = Email.lines[$ctx.lines_read]; | |
with $data { | |
my size_t $len = $_.chars; | |
memcpy($buffer, $_, $len); | |
$ctx.lines_read++; | |
return $len; | |
} | |
return 0; | |
} | |
curl_easy_setopt($_, CURLOPT_READFUNCTION, &read_callback); | |
my ReadContext $ctx .= new; | |
curl_easy_setopt($_, CURLOPT_READDATA, $ctx); | |
curl_easy_setopt($_, CURLOPT_VERBOSE, +True); | |
my $result = curl_easy_perform($_); | |
unless $result ~~ CURLE_OK { | |
warn sprintf("curl_easy_perform failed: %s\n", curl_easy_strerror($result)); | |
} | |
curl_slist_free_all($recipients); | |
curl_easy_cleanup($_); | |
} else { warn "curl failed to initialize" } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment