Related
I am trying to send email from R using MailR package. This works awesome when I try on my personal gmail account. But when I try to run same with my corporate mail id, it doesn't work.
One problem I found is because of 2 step authentication. I have removed 2 step authentication for my personal mail account but unable to for my corporate account. Is there any way I can include a password or authentication in mailR package code?
My code:
library(rJava)
library(mailR)
send.mail(from = "emailid",
to = "emailid",
subject = "Subject of the email",
body = "Please find the attached doc having cluster report",
html = TRUE,
smtp = list(host.name = "smtp.gmail.com",port = 465, user.name="emailid", passwd="*******",ssl = TRUE),
attach.files ="./Prod tracker-new Jul28-Aug2.csv",
authenticate = TRUE,
send = TRUE)
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)
I'm trying to send emails from R using sendmailR package using the following code, which unfortunately fails :
## Set mail contents
from <- sprintf('<sendmailR#%s>', Sys.info()[4])
to <- '<slackline#gmail.com>'
subject <- 'Feeding Plots'
body <- list('Latest feeding graph', mime_part(feeding.plot,
name = "feeding"))
## Set control parameters
control <- sendmail_options(verboseShow = TRUE,
smtpServer ="smtp.gmail.com",
smtpPort = 587,
smtpSTARTTLS = '',
blocking = FALSE)
sendmail(from,
to,
subject,
msg = body,
control = control,
headers)
<< 220 mx.google.com ESMTP xt1sm884721wjb.17 - gsmtp
>> HELO kimura
<< 250 mx.google.com at your service
>> MAIL FROM: <sendmailR#kimura>
<< 530 5.7.0 Must issue a STARTTLS command first. xt1sm884721wjb.17 - gsmtp
Error in wait_for(code) :
SMTP Error: 5.7.0 Must issue a STARTTLS command first. xt1sm884721wjb.17 - gsmtp
The sendmailR manual doesn't mention how to configures STARTTLS although it does indicate that additional arguments can be passed, which is why I have included the option smtpSTARTLS = '' based on whats mentioned in some other threads (here and here). I've tried playing with the argument for smtpSTARTTLS and setting it to TRUE but no joy.
Any pointers to documentation or solutions would be most welcome.
Thanks
As far as I understand it, sendmailR doesn't support any type of login to the SMTP server, hence, gmail is basically unusable. You can only use the package if you are within the right network and set up a server that is only reachable within the network I guess (i.e., one NOT using authentication).
The alternative is the mail package (in which you cannot use your own address).
The reference from the sendmailR documentation is:
SMTP AUTH is currently unsupported.
You could give the new mailR package a shot that allows SMTP authorization: http://cran.r-project.org/web/packages/mailR/index.html
The following call should then work:
send.mail(from = "slackline#gmail.com",
to = "slackline#gmail.com",
subject = "Subject of the email",
body = "Body of the email",
smtp = list(host.name = "smtp.gmail.com", port = 465, user.name = "slackline", passwd = "PASSWORD", ssl = TRUE),
authenticate = TRUE,
send = TRUE)
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.
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
}