Outlook附件保存脚本在Windows命令提示符下不起作用(在RStudio中完美运行)

问题描述 投票:0回答:1

脚本目标将两封电子邮件中的附件文件(.xlsx)保存到网络共享。

问题下面的R脚本在RStudio中效果很好,但是从Windows命令提示符运行时失败。

错误消息

80020009不支持InterfaceSupportsErrorInfocheckErrorInfo -2147352567错误:发生异常。执行中止

R代码

cat("\n##########################################################################################",
    "\n", format(Sys.time(), "%a %m/%d/%Y %X"), ": Starting Daily Attachment Save Script...",
    "\n##########################################################################################")

cat("\n", format(Sys.time(), "%a %m/%d/%Y %X"), ": Setting variables/constants/functions... ")

  library("RDCOMClient")
  library("lubridate")

  TodaysDate  <- Sys.Date()
  StartTime   <- Sys.time()
  currentUser <- Sys.getenv("USERNAME")
  tmpDir      <- Sys.getenv("TEMP")
  report_run_date_main <- Sys.Date()

  SendMail <- function(outFile,
                       ToEmail,
                       EmailSubject,
                       EmailBody,
                       AttachFile = TRUE,
                       CC = "[email protected];"){

    OutApp <- COMCreate("Outlook.Application")
    outMail = OutApp$CreateItem(0)

    outMail[["sentonbehalfofname"]] = "[email protected]"
    outMail[["To"]] = ToEmail
    outMail[["CC"]] = CC
    outMail[["subject"]] = EmailSubject
    outMail[["HTMLBody"]] = paste0("<p>**** SYSTEM GENERATED EMAIL ****</p><br><p>", EmailBody, "</p>", sep = "")
    if (AttachFile == TRUE) {
      outMail[["Attachments"]]$Add(outFile)
    }
    outMail$Send()
    outMail <- NULL
    OutApp <- NULL
  }

  outlook_app <- COMCreate("Outlook.Application")
  search <- outlook_app$AdvancedSearch(
    "Inbox", paste0("(urn:schemas:httpmail:subject like 'EMAIL SUBJECT TO SEARCH%')")
  )
  results <- search$Results()

  save_folder <- paste0(Sys.getenv("USERPROFILE"), "\\Documents")

  get_attachment_names <- function(email) {
    number_attachments = email$Attachments()$Count()
    if (number_attachments == 0) {
      return("")
    }
    attachments <- purrr::map(
      seq(number_attachments), 
      function(x) email$Attachments(x)$FileName()
    )
    return(paste(attachments, sep = ", "))
  }

  msg1 <- ""
  msg2 <- ""

cat("done.")

cat("\n", format(Sys.time(), "%a %m/%d/%Y %X"), ": Saving attachemnts from daily emails... ") 
  for (i in 1:results$Count()) {
    # Error on next line, when run using command line
    gmt_date <- results$Item(i)$ReceivedTime()
    date_received <- as.POSIXct(gmt_date * (24 * 60 * 60), origin="1899-12-30", tz="GMT")

    date_received_dt <- format(date_received, "%Y-%m-%d")
    date_received_tm <- format(date_received, "%H:%M:%S %P")
    date_received_hr <- format(date_received, "%H")

    if(date_received >= Sys.Date()-1) {
      if(date_received_dt==Sys.Date()-1){
        if(date_received_hr>=16){
          email <- results$Item(i)
          attachment_file <- get_attachment_names(email)
          email$Attachments(1)$SaveAsFile(paste0(save_folder, attachment_file))
          msg1 <- paste(format(Sys.time(), "%a %m/%d/%Y %X"), 
                        "<br><br><b>Attachment name:</b>", attachment_file ,
                        "<br><b>Email received on:</b>", date_received, 
                        "<br><b>Subject:</b>", email$Subject(),
                        "<br><b>Save folder:</b>", save_folder)
        }
      } else{
        email <- results$Item(i)
        attachment_file <- get_attachment_names(email)
        email$Attachments(1)$SaveAsFile(paste0(save_folder, attachment_file))
        msg2 <- paste(format(Sys.time(), "%a %m/%d/%Y %X"), 
                      "<br><br><b>Attachment name:</b>", attachment_file ,
                      "<br><b>Email received on:</b>", date_received, 
                      "<br><b>Subject:</b>", email$Subject(),
                      "<br><b>Save folder:</b>", save_folder)
      }
    }
  }
cat("done.")


cat("\n", format(Sys.time(), "%a %m/%d/%Y %X"), ": Notifying users of attachment save status... ")
  if((nchar(msg1)==0)){
    SendMail(outFile = "",
             ToEmail = "[email protected]",
             EmailSubject = paste("[Action Required] Daily Attachment Save Error", Sys.Date()),
             EmailBody = paste("Helpful text 1 for troubleshooting"),
             AttachFile = F, CC = "")
  } else {
    SendMail(outFile = "",
             ToEmail = "[email protected]",
             EmailSubject = paste("Daily attachment saved", Sys.Date()),
             EmailBody = paste(msg1),
             AttachFile = F, CC = "")
  }

  if(nchar(msg2)==0){
    SendMail(outFile = "",
             SendMail(outFile = "",
             ToEmail = "[email protected]",
             EmailSubject = paste("[Action Required] Daily Attachment Save Error", Sys.Date()),
             EmailBody = paste("Helpful text 2 for troubleshooting"),
             AttachFile = F, CC = "")
  } else {
    SendMail(outFile = "",
             ToEmail = "[email protected]",
             EmailSubject = paste("Daily attachment saved", Sys.Date()),
             EmailBody = paste(msg2),
             AttachFile = F, CC = "")
  }
cat("done.")

cat("\n", format(Sys.time(), "%a %m/%d/%Y %X"), ": Garbage Collection... ")
  rm(list=ls())
cat("done.")

cat("\n########################################################################################",
    "\n", format(Sys.time(), "%a %m/%d/%Y %X"), ": Daily Attachment Save Script complete.",
    "\n########################################################################################")

R脚本执行命令

C:\ Progra〜1 \ R \ R-3.4.4 \ bin \ i386 \ Rscript.exe --no-save --no-restore --verbose C:\ Attachments_Save_Script.R>“ C:\ LOGS \ L%date:〜-4,4 %% date:〜-7,2 %% date:〜-10,2%%time:〜0.2 %% time:〜3.2 %% time:〜 6,2%.log“ 2>” C:\ LOGS \ E%date:〜-4,4 %% date:〜-7,2 %% date:〜-10,2%%time:〜0 ,2 %% time:〜3,2 %% time:〜6,2%.log“

版本信息Windows 10 Pro 64位(具有16 GB RAM的i7 vPro)R版本3.4.4(2018-03-15)-“精益求精的人”Microsoft Outlook 2013(15.0.5172.1000)MSO(15.0.5172.1000)32位RStudio 1.0.143

有人在命令行上使用RDCOMClient库遇到此问题吗?有解决办法吗?谢谢。

r outlook save email-attachments rdcomclient
1个回答
0
投票

您的代码从不检查您是否确实有MailItem对象-您也可以具有ReportItemMeetingItem对象,它们不公开ReceivedTime属性。检查Class属性(由所有OOM对象公开)是否== 43OlObjectClass.olMail

© www.soinside.com 2019 - 2024. All rights reserved.