sending mail from R (mailR) - r

I am trying to send mail from R on a windows 7 (home) machine. I tried the following code
send.mail(from = "mymailid#gmail.com",
to = c("mymailid#gmail.com"),
subject = "Subject of the email",
body = "Body of the email",
smtp = list(host.name = "smtp.gmail.com", port = 465, user.name = "myuserid", passwd = "my password", ssl = TRUE),
authenticate = TRUE,
send = TRUE)
I get the following error:
Error in ls(envir = envir, all.names = private) :
invalid 'envir' argument
after that I tried set up an hmail server (with a local domain name and user account, and smtp set up for smtp.gmail.com:25)
send.mail(from = "localuser#localdomain.local",
to = c("mymailid#gmail.com"),
subject = "Subject of the email",
body = "Body of the email",
smtp = list(host.name = "mail.hmailserver.com", port = 25),
authenticate = FALSE,
send = TRUE)
I still get the same error. Any help will be greatly appreciated. Thanks vm

If you're using gmail account, you might need to allow acess to your account from less secure aplications, using this link https://www.google.com/settings/security/lesssecureapps
If you have as well a 2 step verification, you also need to deactivate that.

If your gmail account is propertly setup (as mOnhawk suggested) then this form should work for the smtp list:
smtp = list(host.name = "smtp.gmail.com", port = 465,
ssl=TRUE, user.name = "mymailid#gmail.com",
passwd = "my password)

i am trying to send email using RDCOMClient and here is the code
library(RDCOMClient)
emails <- paste("emailid")
## init com api
OutApp <- COMCreate("Outlook.Application")
## create an email
outMail = OutApp$CreateItem(0)
## configure email parameter
outMail[["To"]] = emails
outMail[["Cc"]] = "emailid"
outMail[["subject"]] = "Monthly Report for Compliance"
outMail[["body"]] = paste(" Please find the monthly report completed for ",Sys.Date(),
".\n\n instrument file is saved at:\n G:\\Data Science\\Monthly Check - Westlake\\Instruments and Issuers Compliance List
"
)
outMail[["attachments"]]$Add("G:\\Data Science\\Monthly Check - Westlake\\Instruments and Issuers Compliance List\\Instruments_tracked-.02202018.csv")
outMail$Send()
I get the below error
<checkErrorInfo> 80020009
No support for InterfaceSupportsErrorInfo
checkErrorInfo -2147352567

You can try the following example:
library(mail)
to <- "albert.physik#gmail.com"
subject <- "mail of R"
msg <- paste("Testing!")
sendmail(to, subject , msg)
But only allows you to send 20 emails per day
I hope you find it useful.
Luck!

Did you use empty string as the body?
I tried with my company email and also gmail. When I put
body = "", # quotation marks with nothing in between
it yields
Error in ls(envir = envir, all.names = private) : invalid 'envir'
argument
While this works:
body = " ", # adding a space there
Don't know why at all... If you happened to have empty string, this might help.
Subject being empty string causes no problem:
subject = "", # quotation marks with nothing in between

Related

Send mail with gmail and R

I am simply trying to send an email with R through my gmail account using the mailR package but it does not seem to work.
I get this error:
Error in .jcall("RJavaTools", "Ljava/lang/Object;", "invokeMethod", cl, :
org.apache.commons.mail.EmailException: Sending the email to the following server failed : aspmx.l.google.com:25
Below is the code with anonymized gmail adresses.
install.packages("mailR")
library(mailR)
sender <- "sender#gmail.com" # Replace with a valid address
recipients <- c("receiver1#gmail.com") # Replace with one or more valid addresses
email <- send.mail(from = sender,
to = recipients,
subject="Subject of the email",
body = "Body of the email",
smtp = list(host.name = "aspmx.l.google.com", port = 25),
authenticate = FALSE,
send = FALSE)
email$send() # execute to send email
I finally managed to make it work ! You have to authorize the app on Google. This link really helped me: https://medium.com/airbnb-engineering/using-googlesheets-and-mailr-packages-in-r-to-automate-reporting-c09579e0377f

Send email in R with attachment [duplicate]

I have a scheduled an R script running from a windows machine.
After it finishes, I wish this script to automatically send an email with some log file attached.
Using shell() with some other scripts may be possible, but I was wondering if there is a better solution within R.
Thanks.
sendmailR works for me on Windows 7. I referenced http://cran.es.r-project.org/web/packages/sendmailR/sendmailR.pdf
smtpServer= info for Outlook 2010 is in File -> Account Settings -> Account Settings -> double click your account -> text in "Server" box
library(sendmailR)
#set working directory
setwd("C:/workingdirectorypath")
#####send plain email
from <- "you#account.com"
to <- "recipient#account.com"
subject <- "Email Subject"
body <- "Email body."
mailControl=list(smtpServer="serverinfo")
sendmail(from=from,to=to,subject=subject,msg=body,control=mailControl)
#####send same email with attachment
#needs full path if not in working directory
attachmentPath <- "subfolder/log.txt"
#same as attachmentPath if using working directory
attachmentName <- "log.txt"
#key part for attachments, put the body and the mime_part in a list for msg
attachmentObject <- mime_part(x=attachmentPath,name=attachmentName)
bodyWithAttachment <- list(body,attachmentObject)
sendmail(from=from,to=to,subject=subject,msg=bodyWithAttachment,control=mailControl)
In addition, multiple files can be sent by adding another mime_part to the msg list as follows (I also condensed it):
attachmentObject <- mime_part(x="subfolder/log.txt",name="log.txt")
attachmentObject2 <- mime_part(x="subfolder/log2.txt",name="log2.txt")
bodyWithAttachment <- list(body,attachmentObject,attachmentObject2)
Use mailR - it works with authentication, attachments, it automatically send txt message along with html and more.
mailR requires rJava which can be a bit of a pain sometimes. On windows I haven't had any problems. On ubuntu this solved the one issue I've had:
sudo apt-get install openjdk-jdk
in R
install.packages("devtools", dep = T)
library(devtools)
install_github("rpremraj/mailR")
(if you have trouble with rJava - try sudo R CMD javareconf in terminal)
mailR is easy to work with and well documented on the github page.
Example from the documentaion
library(mailR)
send.mail(from = "sender#gmail.com",
to = c("recipient1#gmail.com", "recipient2#gmail.com"),
subject = "Subject of the email",
body = "Body of the email",
smtp = list(host.name = "smtp.gmail.com", port = 465, user.name = "gmail_username", passwd = "password", ssl = TRUE),
authenticate = TRUE,
send = TRUE,
attach.files = c("./download.log", "upload.log", "https://dl.dropboxusercontent.com/u/5031586/How%20to%20use%20the%20Public%20folder.rtf"),
file.names = c("Download log.log", "Upload log.log", "DropBox File.rtf"), # optional parameter
file.descriptions = c("Description for download log", "Description for upload log", "DropBox File"), # optional parameter
debug = TRUE)
Note: your smtp server might find excessive use suspicious. This is the case with e.g. gmail. So after sending a few mails you probably have to log in to the gmail account and see if the account has been temporarily disabled. Also note that if you use a gmail account with two-factor authentication you need to use an application specific password.
Would you settle for a twitter message? You could use Rcurl to post an update to twitter, which can then be forwarded to your cell phone as a text, or to your email via the notification settings.
See here: http://www.sakana.fr/blog/2007/03/18/scripting-twitter-with-curl/
Have you looked into the sendmailR package yet? It allows SMTP to submit a message and you could probably edit the function to allow an attachment. Then again, if its only one log file it might just be worth it to use shell() as you mentioned.
For Windows one might parse together a VB-Script (see e.g. http://www.paulsadowski.com/wsh/cdo.htm ) and then call it via shell.
This might look like this:
SendMail <- function(from="me#my-server.de",to="me#my-server.de",text="Hallo",subject="Sag Hallo",smtp="smtp.my.server.de",user="me.myself.and.i",pw="123"){
require(stringr)
part1 <- "Const cdoSendUsingPickup = 1 'Send message using the local SMTP service pickup directory.
Const cdoSendUsingPort = 2 'Send the message using the network (SMTP over the network).
Const cdoAnonymous = 0 'Do not authenticate
Const cdoBasic = 1 'basic (clear-text) authentication
Const cdoNTLM = 2 'NTLM "
part2 <- paste(paste("Set objMessage = CreateObject(",'"',"CDO.Message",'"',")" ,sep=""),
paste("objMessage.Subject = ",'"',subject,'"',sep=""),
paste("objMessage.From = ",'"',from,'"',sep=""),
paste("objMessage.To = ",'"',to,'"',sep=""),
paste("objMessage.TextBody = ",'"',text,'"',sep=""),
sep="\n")
part3 <- paste(
"'==This section provides the configuration information for the remote SMTP server.
objMessage.Configuration.Fields.Item _
(\"http://schemas.microsoft.com/cdo/configuration/sendusing\") = 2
'Name or IP of Remote SMTP Server
objMessage.Configuration.Fields.Item _
(\"http://schemas.microsoft.com/cdo/configuration/smtpserver\") = ",'"',smtp,'"',"
'Type of authentication, NONE, Basic (Base64 encoded), NTLM
objMessage.Configuration.Fields.Item _
(\"http://schemas.microsoft.com/cdo/configuration/smtpauthenticate\") = cdoBasic
'Your UserID on the SMTP server
objMessage.Configuration.Fields.Item _
(\"http://schemas.microsoft.com/cdo/configuration/sendusername\") = ",'"',user,'"',"
'Your password on the SMTP server
objMessage.Configuration.Fields.Item _
(\"http://schemas.microsoft.com/cdo/configuration/sendpassword\") = ",'"',pw,'"', "
'Server port (typically 25)
objMessage.Configuration.Fields.Item _
(\"http://schemas.microsoft.com/cdo/configuration/smtpserverport\") = 25
'Use SSL for the connection (False or True)
objMessage.Configuration.Fields.Item _
(\"http://schemas.microsoft.com/cdo/configuration/smtpusessl\") = False
'Connection Timeout in seconds (the maximum time CDO will try to establish a connection to the SMTP server)
objMessage.Configuration.Fields.Item _
(\"http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout\") = 60
objMessage.Configuration.Fields.Update
'==End remote SMTP server configuration section==
objMessage.Send
",sep="")
vbsscript <- paste(part1,part2,part3,sep="\n\n\n")
str_split(vbsscript,"\n")
writeLines(vbsscript, "sendmail.vbs")
shell("sendmail.vbs")
unlink("sendmail.vbs")
}
Just want to remind people who wants self-notifying feature of a service called twilio, they provide free service to send sms to your own cellphone. A walk-through using R is available here https://dreamtolearn.com/ryan/data_analytics_viz/78
An example code is attached, just replace the credentials with the ones of your own.
library(jsonlite)
library(XML)
library(httr)
library(rjson)
library(RCurl)
options(RCurlOptions = list(cainfo = system.file("CurlSSL", "cacert.pem", package = "RCurl")))
authenticate_twilio <- "https://[ACCOUNT SID]:[AUTH TOKEN]#api.twilio.com/2010-04-01/Accounts"
authenticate_response <- getURL(authenticate_twilio)
print(authenticate_response)
postForm("https://[ACCOUNT SID]:[AUTH TOKEN]#api.twilio.com/2010-04-01/Accounts/[ACCOUNT SID]/Messages.XML",.params = c(From = "+1[twilio phone#]", To = "+1[self phone#]",Body = "Hello from twilio"))
Here is a simple code snippet for sending an e-mail by using "mailR" package
library(mailR)
# 1. Sender
sender <- "x#me.com"
# 2. Recipients
recipients <- c("y#you.com", "z#our.com")
# 3. Attached files
list_files_attached_location <- c("mtcars.csv")
list_files_attached_names <- c("mtcars name")
list_files_attached_description <- c("mtcars desc")
# 4. Send email
tryCatch({
send.mail(from = sender,
to = recipients,
subject = "Your subject",
body = "Your mail body",
smtp = list(
host.name = "smtp.gmail.com",
port = 465,
user.name = sender,
passwd = "psw",
ssl = TRUE),
authenticate = TRUE,
send = TRUE,
attach.files = list_files_attached_location,
file.names = list_files_attached_names,
file.descriptions = list_files_attached_description,
debug = TRUE
)
},
error = function(e) {
print(e)
stop()
})
For those who suggested using 'mailR' - this is the way to go, but it is difficult to install of ubuntu. Here is a resource to install 'javaR' on ubuntu which will allow you to install 'mailR'
https://www.r-bloggers.com/2018/02/installing-rjava-on-ubuntu/
Late to this, but you can avoid shelling out to vbscript by using RDCOMClient correctly, as in this example from R-Help.
> sendEmail(ema = "r-help at r-project.org",
name = "R-help mailing list",
subject = "How to send Email from R using the RDCOMClient"
msgBody = "here is the body of the message")
The package RDCOMClient is available at http://www.omegahat.org/RDCOMClient.
"sendEmail" <-
function(ema, name, subject, msgBody, deliverNow = TRUE)
{
require(RDCOMClient)
ema <- paste("SMPT:", ema, sep="") ## prepend protocol to address
## create an e-mail session
session <- COMCreate("Mapi.Session")
session$Logon()
## add a message to the outbox collection of messages
outbox <- session[["Outbox"]]
msg <- outbox[["Messages"]]$Add(subject, msgBody)
## add recipient's name (TODO: addMultiple() or loop, if many recipients)
msg[["Recipients"]]$Add(name, ema)
msg$Send()
if(deliverNow)
msg$DeliverNow()
session$Logoff() ## wrap up
}

how do you send email from R

I want to send emails from R. This is what I have so far:
library(sendmailR)
from <- "eamil#example.com"
to <- "email2#example.com"
subject <- "Performance Result"
body <- "This is the result of the test:"
mailControl=list(smtpServer="snmpt server address")
sendmail(from=from,to=to,subject=subject,msg=body,control=mailControl)
When I execute this script, my R session hangs. Any ideas what might be happening?
If you need to be able to use an smtp server with authentication you can use the mailR package.
For example using gmail's smtp server:
library(mailR)
sender <- "SENDER#gmail.com"
recipients <- c("RECIPIENT#gmail.com")
send.mail(from = sender,
to = recipients,
subject = "Subject of the email",
body = "Body of the email",
smtp = list(host.name = "smtp.gmail.com", port = 465,
user.name = "YOURUSERNAME#gmail.com",
passwd = "YOURPASSWORD", ssl = TRUE),
authenticate = TRUE,
send = TRUE)
I just tried it out, and it worked for me.
My only differences were I used <> for the from and to:
from = "<email1#dal.ca>"
to = "<email2#gmail.com>"
and my mail control was different, I used
control=list(smtpServer="ASPMX.L.GOOGLE.COM"))
Sorry for bumping up this thread. If you want to send email from R using Microsoft outlook, below is the way to go using the RDCOMClient package. I myself spent a lot of time trying to find an answer on this. I thought it would be useful to have this solution too in this thread for users.
Full credit to #agstudy who provided the original solution in this link - Sending email in R via outlook
library (RDCOMClient)
OutApp <- COMCreate("Outlook.Application")
outMail = OutApp$CreateItem(0)
outMail[["To"]] = "test#test.com"
outMail[["subject"]] = "Test Subject"
outMail[["body"]] = "Body of email"
outMail$Send()
library(mailR)
sender <- "abc#gmail.com"
recipients <- c("bcd#gmail.com","xyz#gmail.com")
send.mail(
from = sender,
to = recipients,
subject="Cash_Collected_Bank_transfer",
Sys.Date(),
"{}", body = Summary1, encoding = "utf-8", smtp =
list(host.name = "smtp.gmail.com", port = 465,
user.name="abc#gmail.com", passwd="abc#1234", ssl=TRUE),
authenticate = TRUE, send = TRUE ,
attach.files = c(path2), html = TRUE , inline = TRUE )
There is a new package called emayili with two very interesting promises:
works on all manner of SMTP servers
has minimal dependencies (or dependencies which are easily satisfied)
It seems early stages but promising nonetheless. Sending email is as simple as:
devtools::install_github("datawookie/emayili")
library(emayili)
library(dplyr)
email <- envelope() %>%
from("alice#yahoo.com") %>%
to("bob#google.com") %>%
subject("This is a plain text message!") %>%
body("Hello!")
smtp <- server(host = "smtp.gmail.com",
port = 465,
username = "bob#gmail.com",
password = "bd40ef6d4a9413de9c1318a65cbae5d7")
smtp(email, verbose = TRUE)
There are two ways to send an email via Gmail, anonymized or authenticated. Here is the code for anonymized:
library(mailR)
send.mail(from = "sender#gmail.com",
to = c("Recipient 1 <recipient1#gmail.com>", "recipient2#gmail.com"),
cc = c("CC Recipient <cc.recipient#gmail.com>"),
bcc = c("BCC Recipient <bcc.recipient#gmail.com>"),
subject = "Subject of the email",
body = "Body of the email",
smtp = list(host.name = "aspmx.l.google.com", port = 25),
authenticate = FALSE,
send = TRUE)
Make sure the recipient emails are Gmail too. It most likely goes to the spam folder in the Gmail account so make sure to mark it "not spammed".
You can find more info here.
I found the simplest way in Ubuntu is to run the one liner Terminal command in R.
No need for password.
try(system("mutt -s 'Run is complete.' youremail#anymail.com < /dev/null", intern = TRUE))
You will need to install mutt in terminal before this.
If you prefer an in-house solution with your server, you can call the linux sendmail.
EMAIL <- myEmail#gmail.com
cmd <- 'subject="Info server";body="This is an email"'
cmd <- paste("echo -e \"Subject:${subject}\n${body}\" | /usr/sbin/sendmail -t \"", EMAIL, "\"")
system(cmd)

Send Mail R and Socket Connections

I am attempting to use the SendMailR function, I have checked with our I.T. department that I am using the correct server and I have the right permissions to connect and they have sent emails via this server but not through R and I have also checked that the port should be 25.
The code:
# E-Mail #
library(sendmailR)
from <- "david#work.com"
to <- "adam#work.com"
subject <- "Send Mail R- Test"
body <- "TESTING TESTING TESTING"
mailControl=list(smtpServer="uksmtp.global.local")
sendmail(from=from,to=to,subject=subject,msg=body,control=mailControl)
I receive the below error:
function (host = "localhost", port, server = FALSE, blocking = FALSE,
open = "a+", encoding = getOption("encoding"), timeout = getOption("timeout"))
.Internal(socketConnection(host, port, server, blocking, open,
encoding, timeout))
<bytecode: 0x00000000071beb18>
<environment: namespace:base>
So I figured its an error with or I needed to define a new socket connection, is this where the problem lies? Could anyone give me any pointers on where to go next with this to get it working?
Thanks in advance
Although this is not an answer to your question you might want to alternatively check out the mail package which offers an alternative way to sent mail via an external mail server and address:
require(mail)
sendmail("adam#work.com", "Send Mail R- Test", "TESTING TESTING TESTING")
Note that you can only sent 20 mails that way per day (to avoid spam).
You could give the new mailR package a shot that allows SMTP authorization: http://cran.r-project.org/web/packages/mailR
The following call should then work:
send.mail(from = "sender#gmail.com",
to = "recipient#gmail.com",
subject = "Subject of the email",
body = "Body of the email",
smtp = list(host.name = "smtp.gmail.com", port = 465, user.name = "recipient", passwd = "PASSWORD", ssl = TRUE, tls = TRUE),
authenticate = TRUE,
send = TRUE)
Just replace the key-value pairs in the parameter smtp and you should be set to go.

How to send an email with attachment from R in windows

I have a scheduled an R script running from a windows machine.
After it finishes, I wish this script to automatically send an email with some log file attached.
Using shell() with some other scripts may be possible, but I was wondering if there is a better solution within R.
Thanks.
sendmailR works for me on Windows 7. I referenced http://cran.es.r-project.org/web/packages/sendmailR/sendmailR.pdf
smtpServer= info for Outlook 2010 is in File -> Account Settings -> Account Settings -> double click your account -> text in "Server" box
library(sendmailR)
#set working directory
setwd("C:/workingdirectorypath")
#####send plain email
from <- "you#account.com"
to <- "recipient#account.com"
subject <- "Email Subject"
body <- "Email body."
mailControl=list(smtpServer="serverinfo")
sendmail(from=from,to=to,subject=subject,msg=body,control=mailControl)
#####send same email with attachment
#needs full path if not in working directory
attachmentPath <- "subfolder/log.txt"
#same as attachmentPath if using working directory
attachmentName <- "log.txt"
#key part for attachments, put the body and the mime_part in a list for msg
attachmentObject <- mime_part(x=attachmentPath,name=attachmentName)
bodyWithAttachment <- list(body,attachmentObject)
sendmail(from=from,to=to,subject=subject,msg=bodyWithAttachment,control=mailControl)
In addition, multiple files can be sent by adding another mime_part to the msg list as follows (I also condensed it):
attachmentObject <- mime_part(x="subfolder/log.txt",name="log.txt")
attachmentObject2 <- mime_part(x="subfolder/log2.txt",name="log2.txt")
bodyWithAttachment <- list(body,attachmentObject,attachmentObject2)
Use mailR - it works with authentication, attachments, it automatically send txt message along with html and more.
mailR requires rJava which can be a bit of a pain sometimes. On windows I haven't had any problems. On ubuntu this solved the one issue I've had:
sudo apt-get install openjdk-jdk
in R
install.packages("devtools", dep = T)
library(devtools)
install_github("rpremraj/mailR")
(if you have trouble with rJava - try sudo R CMD javareconf in terminal)
mailR is easy to work with and well documented on the github page.
Example from the documentaion
library(mailR)
send.mail(from = "sender#gmail.com",
to = c("recipient1#gmail.com", "recipient2#gmail.com"),
subject = "Subject of the email",
body = "Body of the email",
smtp = list(host.name = "smtp.gmail.com", port = 465, user.name = "gmail_username", passwd = "password", ssl = TRUE),
authenticate = TRUE,
send = TRUE,
attach.files = c("./download.log", "upload.log", "https://dl.dropboxusercontent.com/u/5031586/How%20to%20use%20the%20Public%20folder.rtf"),
file.names = c("Download log.log", "Upload log.log", "DropBox File.rtf"), # optional parameter
file.descriptions = c("Description for download log", "Description for upload log", "DropBox File"), # optional parameter
debug = TRUE)
Note: your smtp server might find excessive use suspicious. This is the case with e.g. gmail. So after sending a few mails you probably have to log in to the gmail account and see if the account has been temporarily disabled. Also note that if you use a gmail account with two-factor authentication you need to use an application specific password.
Would you settle for a twitter message? You could use Rcurl to post an update to twitter, which can then be forwarded to your cell phone as a text, or to your email via the notification settings.
See here: http://www.sakana.fr/blog/2007/03/18/scripting-twitter-with-curl/
Have you looked into the sendmailR package yet? It allows SMTP to submit a message and you could probably edit the function to allow an attachment. Then again, if its only one log file it might just be worth it to use shell() as you mentioned.
For Windows one might parse together a VB-Script (see e.g. http://www.paulsadowski.com/wsh/cdo.htm ) and then call it via shell.
This might look like this:
SendMail <- function(from="me#my-server.de",to="me#my-server.de",text="Hallo",subject="Sag Hallo",smtp="smtp.my.server.de",user="me.myself.and.i",pw="123"){
require(stringr)
part1 <- "Const cdoSendUsingPickup = 1 'Send message using the local SMTP service pickup directory.
Const cdoSendUsingPort = 2 'Send the message using the network (SMTP over the network).
Const cdoAnonymous = 0 'Do not authenticate
Const cdoBasic = 1 'basic (clear-text) authentication
Const cdoNTLM = 2 'NTLM "
part2 <- paste(paste("Set objMessage = CreateObject(",'"',"CDO.Message",'"',")" ,sep=""),
paste("objMessage.Subject = ",'"',subject,'"',sep=""),
paste("objMessage.From = ",'"',from,'"',sep=""),
paste("objMessage.To = ",'"',to,'"',sep=""),
paste("objMessage.TextBody = ",'"',text,'"',sep=""),
sep="\n")
part3 <- paste(
"'==This section provides the configuration information for the remote SMTP server.
objMessage.Configuration.Fields.Item _
(\"http://schemas.microsoft.com/cdo/configuration/sendusing\") = 2
'Name or IP of Remote SMTP Server
objMessage.Configuration.Fields.Item _
(\"http://schemas.microsoft.com/cdo/configuration/smtpserver\") = ",'"',smtp,'"',"
'Type of authentication, NONE, Basic (Base64 encoded), NTLM
objMessage.Configuration.Fields.Item _
(\"http://schemas.microsoft.com/cdo/configuration/smtpauthenticate\") = cdoBasic
'Your UserID on the SMTP server
objMessage.Configuration.Fields.Item _
(\"http://schemas.microsoft.com/cdo/configuration/sendusername\") = ",'"',user,'"',"
'Your password on the SMTP server
objMessage.Configuration.Fields.Item _
(\"http://schemas.microsoft.com/cdo/configuration/sendpassword\") = ",'"',pw,'"', "
'Server port (typically 25)
objMessage.Configuration.Fields.Item _
(\"http://schemas.microsoft.com/cdo/configuration/smtpserverport\") = 25
'Use SSL for the connection (False or True)
objMessage.Configuration.Fields.Item _
(\"http://schemas.microsoft.com/cdo/configuration/smtpusessl\") = False
'Connection Timeout in seconds (the maximum time CDO will try to establish a connection to the SMTP server)
objMessage.Configuration.Fields.Item _
(\"http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout\") = 60
objMessage.Configuration.Fields.Update
'==End remote SMTP server configuration section==
objMessage.Send
",sep="")
vbsscript <- paste(part1,part2,part3,sep="\n\n\n")
str_split(vbsscript,"\n")
writeLines(vbsscript, "sendmail.vbs")
shell("sendmail.vbs")
unlink("sendmail.vbs")
}
Just want to remind people who wants self-notifying feature of a service called twilio, they provide free service to send sms to your own cellphone. A walk-through using R is available here https://dreamtolearn.com/ryan/data_analytics_viz/78
An example code is attached, just replace the credentials with the ones of your own.
library(jsonlite)
library(XML)
library(httr)
library(rjson)
library(RCurl)
options(RCurlOptions = list(cainfo = system.file("CurlSSL", "cacert.pem", package = "RCurl")))
authenticate_twilio <- "https://[ACCOUNT SID]:[AUTH TOKEN]#api.twilio.com/2010-04-01/Accounts"
authenticate_response <- getURL(authenticate_twilio)
print(authenticate_response)
postForm("https://[ACCOUNT SID]:[AUTH TOKEN]#api.twilio.com/2010-04-01/Accounts/[ACCOUNT SID]/Messages.XML",.params = c(From = "+1[twilio phone#]", To = "+1[self phone#]",Body = "Hello from twilio"))
Here is a simple code snippet for sending an e-mail by using "mailR" package
library(mailR)
# 1. Sender
sender <- "x#me.com"
# 2. Recipients
recipients <- c("y#you.com", "z#our.com")
# 3. Attached files
list_files_attached_location <- c("mtcars.csv")
list_files_attached_names <- c("mtcars name")
list_files_attached_description <- c("mtcars desc")
# 4. Send email
tryCatch({
send.mail(from = sender,
to = recipients,
subject = "Your subject",
body = "Your mail body",
smtp = list(
host.name = "smtp.gmail.com",
port = 465,
user.name = sender,
passwd = "psw",
ssl = TRUE),
authenticate = TRUE,
send = TRUE,
attach.files = list_files_attached_location,
file.names = list_files_attached_names,
file.descriptions = list_files_attached_description,
debug = TRUE
)
},
error = function(e) {
print(e)
stop()
})
For those who suggested using 'mailR' - this is the way to go, but it is difficult to install of ubuntu. Here is a resource to install 'javaR' on ubuntu which will allow you to install 'mailR'
https://www.r-bloggers.com/2018/02/installing-rjava-on-ubuntu/
Late to this, but you can avoid shelling out to vbscript by using RDCOMClient correctly, as in this example from R-Help.
> sendEmail(ema = "r-help at r-project.org",
name = "R-help mailing list",
subject = "How to send Email from R using the RDCOMClient"
msgBody = "here is the body of the message")
The package RDCOMClient is available at http://www.omegahat.org/RDCOMClient.
"sendEmail" <-
function(ema, name, subject, msgBody, deliverNow = TRUE)
{
require(RDCOMClient)
ema <- paste("SMPT:", ema, sep="") ## prepend protocol to address
## create an e-mail session
session <- COMCreate("Mapi.Session")
session$Logon()
## add a message to the outbox collection of messages
outbox <- session[["Outbox"]]
msg <- outbox[["Messages"]]$Add(subject, msgBody)
## add recipient's name (TODO: addMultiple() or loop, if many recipients)
msg[["Recipients"]]$Add(name, ema)
msg$Send()
if(deliverNow)
msg$DeliverNow()
session$Logoff() ## wrap up
}

Resources