Search code examples
javascriptarraysobjectmailto

How to format a text in a mailto function


I have two arrays and an object. One array conatins product codes, and another contains the quantities thereof. For example, the first quantity in the quantities array is the quantity of the product code that is the first one in the product code array. I also have an object that contains customer data. It would look something like this:

customer={
name:' firstname lastname',
email: 'example@domain.com',
company: "company name",
phone_number: 'phone number',
}

the arrays would look like this:

product_codes=[code_1; code_2; code_3];
quantities=[23, 56, 45];

Say that all of this is being mailed to customersupport@example.com.

I am familiar with the basics of the mailto function, but I would like to know if there is a way to format the body of the email so that it looks something like this:

...................................

Name: customer.name

email: customer.email

company name: customer.company

phone number: customer.phone_number

product code 1: corresponding quantity

product code 2: corresponding quantity

product code 3: corresponding quantity

...............................................

I would also like to be able to add any other given codes and quantities, as I am not sure of how many there will be. Is this even possible? If so, how? Please explain so that I can not only use it, but also understand how it works. Thanks!

If I'm not being clear enough, please let me know so I can edit it for greater clarity.


Solution

  • var sendEmail = function() {
    
      var customer, body, quantities, product_codes;    
    
      customer = {
        name: 'First Last',
        email: 'example@example.com',
        company: 'Company',
        phone_number: 'phone number',
      }
    
      body =  'Name: '+ customer.name;
      body += '\nEmail: '+ customer.email;
      body += '\nCompany: '+ customer.company;
      body += '\nPhone Number: '+ customer.phone_number;
    
      product_codes = ['code_1', 'code_2', 'code_3'];
      quantities = [23, 56, 45];
    
      for(var i = 0; i < product_codes.length; i += 1) {
        body += '\nProduct Code '+ product_codes[i] +': '+ quantities[i];
      }
    
      subject = 'Your Subject';
    
      window.location = 'mailto:customersupport@example.com?body='+ encodeURIComponent(body) +'&subject='+ encodeURIComponent(subject);
    
    };
    
    // execute this function when the user clicks the #send-email button
    var button = document.getElementById('send-email');
    button.addEventListener('click', sendEmail);
    

    This is how the email will look like