title: cannot send email via outlook in ruby
body: <p>I have a script where the syntax works using irb but not via the ruby program.
  The script fails at the message1.Send line. However this syntax works when I execute it under irb.</p>
  
  <pre><code>**P:/RubyAutoEmail.rb:23:in `method_missing': (in OLE method `Send': ) (WIN32OLERuntimeError)**
      OLE error code:4096 in Microsoft Outlook
        Outlook does not recognize one or more names.
      HRESULT error code:0x80020009
        Exception occurred.
          from P:/RubyAutoEmail.rb:23:in `block in sendemail'
          from P:/RubyAutoEmail.rb:12:in `each'
          from P:/RubyAutoEmail.rb:12:in `sendemail'
          from P:/RubyAutoEmail.rb:35:in `&lt;main&gt;'
  </code></pre>
  
  <p>For example. here you can see that the message1.Send works</p>
  
  <pre><code>    irb(main):002:0&gt; require 'win32ole'
  =&gt; true
  irb(main):003:0&gt; outlook = WIN32OLE.new('Outlook.Application')
  =&gt; #&lt;WIN32OLE:0x0000000327a8c8&gt;
  irb(main):004:0&gt; mapi = outlook.GetNameSpace('MAPI')
  =&gt; #&lt;WIN32OLE:0x000000030e53a0&gt;
  irb(main):005:0&gt; drafts = mapi.GetDefaultFolder(16)
  =&gt; #&lt;WIN32OLE:0x000000032a8778&gt;
  irb(main):006:0&gt;  drafts.Items.each do |message|
  irb(main):007:1*  if message.Subject =~ /test email/i
  irb(main):008:2&gt; message1 = outlook.CreateItem(0)
  irb(main):009:2&gt; message1.Subject
  irb(main):010:2&gt; message1.To='junkone2@dd.com'
  irb(main):011:2&gt; message1.Send
  irb(main):012:2&gt; end
  irb(main):013:1&gt; end
  =&gt; nil
  </code></pre>
  
  <p>However, when I write it using a script, it fails. </p>
  
  <pre><code>    require 'win32ole'
  
      def sendemail(outlook, foldernumber, templatename,nameplaceholder,actualname,emailid)
      mapi = outlook.GetNameSpace('MAPI')
   drafts = mapi.GetDefaultFolder(foldernumber)
  
   # Iterate over messages in a folder:
  
   drafts.Items.each do |message|
  
      # Your code here...
   if message.Subject =~ /test email/i
  # if message.Subject.downcase.include?(templatename.downcase)
  message1 = outlook.CreateItem(0)
  message1.Subject=message.Subject
  message1.Body=message.Body
  message1.Body=message1.Body.gsub(nameplaceholder,actualname)
  message1.To=emailid
  message1.Save
  message1.Send
  
    end
      end  
      end
  
      outlook = WIN32OLE.new('Outlook.Application')
  
  
  # constant numbers
  #https://msdn.microsoft.com/en-us/library/office/aa219371(v=office.11).aspx
  
   sendemail(outlook,16, "test email","&lt;TBD&gt;","Junkee","junkone97@gmail")
  
   #https://stackoverflow.com/questions/12593166/whats-the-easiest-way-to-send-a-message-through-outlook-with-ruby
  </code></pre>