简体   繁体   中英

Problem creating an email with an attachment in Javascript

I'm initiating an email create, by calling the code below, and adding an attachment to it.

I want the user to be able to type in the receipient, and modify the contents of the message, so I'm not sending it immediately.

Why do I get a RangeError the 2nd time the method is called?
(The first time it works correctly.)

function NewMailItem(p_recipient, p_subject, p_body, p_file, p_attachmentname)
{
   try 
   {
     var objO = new ActiveXObject('Outlook.Application');
     var objNS = objO.GetNameSpace('MAPI');
     var mItm = objO.CreateItem(0);
     mItm.Display();
     if (p_recipient.length > 0) 
     {
       mItm.To = p_recipient;
     }
     mItm.Subject = p_subject;
     if (p_file.length > 0) 
     {
      var mAts = mItm.Attachments;
      mAts.add(p_file, 1, p_body.length + 1, p_attachmentname);
     }
     mItm.Body = p_body;
     mItm.GetInspector.WindowState = 2;
   } catch(e) 
   { 
     alert('unable to create new mail item'); 
   } 
}

The error is occuring on the mAts.add line. So when it tries to attach the document, it fails.

Also the file name (p_file) is a http address to a image.

Won't work outside of IE, the user needs to have Outlook on the machine and an account configured on it. Are you sure you want to send an email this way?

I'm trying it with this little snippet, and it works flawlessly:

var objO = new ActiveXObject('Outlook.Application');
var mItm = objO.CreateItem(0);

var mAts   = mItm.Attachments;
var p_file = [
  "http://stackoverflow.com/content/img/vote-arrow-up.png",
  "http://stackoverflow.com/content/img/vote-arrow-down.png"
];
for (var i = 0; i < p_file.length; i++) {
  mAts.add(p_file[i]);
}

Note that I left off all optional arguments to Attachments.Add() . The method defaults to adding the attachments at the end, which is what you seem to want anyway.

Can you try this standalone snippet? If it works for you, please do a step-by-step reduction of your code towards this absolute minimum, and you will find what causes the error.

first do mItm.display() then write mItm.GetInspector.WindowState = 2; this will work

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM