67

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?

isomorphismes
  • 7,975
  • 9
  • 55
  • 69
user1471980
  • 10,383
  • 47
  • 132
  • 225
  • 1
    It would be awesome know how to solve this problem I always got error trying to use this function @user1471980 – Duck May 01 '14 at 18:08
  • 1
    what's your operating system? – Matthew Plourde May 01 '14 at 18:25
  • Does [mailR](https://github.com/rpremraj/mailR) work using the same config? – lukeA May 01 '14 at 18:30
  • You need to set a valid `smtpServer` and valid email address in `to`. Not to mention that this is a duplicate http://stackoverflow.com/questions/2885660/how-to-send-email-with-attachment-from-r-in-windows – David Arenburg May 01 '14 at 19:15
  • @Duck sure it works on Windows or any other operating system, you just need an SMTP somewhere, probably not on your machine running R. E.g. you can use your ISP's mail server. – daroczig May 05 '14 at 21:34
  • Thanks dear @daroczig I think the problem is with outlook because it doesn't give me SMTP direction. Maybe any advice of how to get it. – Duck May 06 '14 at 14:41
  • I tried the mailR, sendmailR, and [blastula](https://rich-iannone.github.io/blastula/reference/smtp_send.html) suggestions with no success. And [SMS from R via Twilio](http://seankross.com/2017/03/07/Send-a-Text-from-R-with-Twilio.html) didn't appeal to me. Finally settled on a less elegant but simple solution: write a text file to OneDrive, which I never use, and allow notifications on my phone because all I wanted was a notification when a long-running model finished. Could have been any cloud drive, but I don't allow notifications from Dropbox because they would be too frequent. – Tanya Murphy Oct 31 '19 at 21:50

8 Answers8

49

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)
alko989
  • 7,298
  • 5
  • 41
  • 60
  • 8
    I recieve such an error: `Error in ls(envir = envir, all.names = private) : invalid 'envir' argument` – Marcin Kosiński Mar 15 '15 at 16:46
  • 1
    I cannot replicate your error. The code works for me like it is. Consider asking a new question where you describe how to reproduce this error and probably someone will be able to help you. Maybe [this](https://github.com/rpremraj/mailR/issues/15) helps. – alko989 Mar 16 '15 at 12:01
  • @MarcinKosinski I got that error as well but then restarted R and it worked for me. – isomorphismes May 12 '15 at 06:31
  • Worked so far so good for me, using a corporate Google Apps account. Tks.+1 – Murta Nov 27 '15 at 16:14
  • does this still work? I get a critical security warning mail from google when attempting it and then on R side `Error: EmailException (Java): Sending the email to the following server failed : smtp.gmail.com:465`. Am i assuming correctly that `SENDER@gmail.com` and `YOURUSERNAME@gmail.com` would be the same? – Tonio Liebrand Sep 21 '19 at 21:27
  • 1
    @BigDataScientist the code still works if you [allow less secure apps access](https://myaccount.google.com/lesssecureapps) in your gmail settings. The question is if you want to accept any risks associated with it. – alko989 Sep 23 '19 at 11:51
  • thanks that helped when i tried it locally. On EC2 it still fails unfortunately, will keep looking. – Tonio Liebrand Sep 27 '19 at 18:49
  • 1
    @BigDataScientist there are many SMTP providers (most of them with free tiers for few hundred emails per month). If you are using EC2, Amazon offers free SMTP server for the first 62000 emails called [Amazon SES](https://aws.amazon.com/ses/pricing/) – alko989 Sep 28 '19 at 21:48
23

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"))
Sarah
  • 721
  • 7
  • 15
  • 2
    I am using Windows (8.1), but I don't use outlook, so I'm not sure about that. – Sarah May 02 '14 at 01:13
  • Thanks @Sarah maybe do you know how to get `smtpServer` on Windows – Duck May 02 '14 at 13:49
  • @Duck What would it mean for R to be able to send mail on Outlook? – isomorphismes May 12 '15 at 06:28
  • @isomorphismes Considering microsoft office outlook – Duck May 12 '15 at 16:01
  • 1
    @Duck The mail can be sent through R `xor` Outlook; those options are mutually exclusive. – isomorphismes May 13 '15 at 15:09
  • This does not work for me anymore ( it did an year ago). I used `sendmail` with the above-mentioned SMTP server, but it gave me an error ```In socketConnection(host = server, port = port, blocking = TRUE) : ASPMX.L.GOOGLE.COM:25 cannot be opened``` – Chintan Pathak Jul 25 '19 at 19:01
  • Using the `` around the "from" address allowed me to send "from" a shared office email mailbox (while still authenticating using my own email address and password). Thanks for this tip! – Kalin Aug 30 '19 at 21:07
18

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()
Code_Sipra
  • 1,461
  • 3
  • 16
  • 35
7
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 )
MadmanLee
  • 396
  • 4
  • 18
Piyush Sharma
  • 71
  • 1
  • 1
  • 4
    Although your answer may be correct, it is preferable to add explanatory text to help readers understand your code. – vincentmajor Apr 11 '17 at 16:40
  • 1
    is there a way to encrypt the password? – DJ_Stuffy_K May 15 '19 at 23:10
  • 2
    @DJ_Stuffy_K: Saw this 4 yrs later, but here is my approach is to set environment variable for the password in R (for anyone who will stumble upon this) First write your password on your environment variable `Sys.setenv(GMAIL_PWD = 'mypassword')` Then call your env variable in your script `passwd = Sys.getenv("GMAIL_PWD")` This way you do not need to hardcode your password on the script. You could do the same thing with other variables – x85ms16 May 28 '19 at 18:26
  • Note, you may need to use `` in the "from" field to send from another mailbox address (see other answer https://stackoverflow.com/a/23413965/1255931). – Kalin Aug 30 '19 at 21:09
5

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)
Gorka
  • 2,812
  • 1
  • 25
  • 32
  • can I use the same SMTP server if I am sending a message from a Yahoo account. Also, is this the email/pwd of sender or receiver? – Chintan Pathak Jul 25 '19 at 23:37
2

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.

Habib Karbasian
  • 475
  • 6
  • 17
1

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.

entropy
  • 171
  • 11
0

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)      
Xavier Prudent
  • 1,423
  • 2
  • 22
  • 48