title: Sending JavaMail from Multiple Email Accounts
body: <p>I have a program where I have a number of users which each could be sending emails from different email accounts.</p>
  
  <p>When I try to use JavaMail to send emails. They always get sent out by the account of the user who sent an email first.</p>
  
  <pre><code>user1 = new User("dummy-email@gmail.com", "dumpass12");
  user2 = new User("second-dummy@gmail.com", "secondpass12");
  
  user1.sendMail(toAddress, subject, body);
  user2.sendMail(toAddress, subject, body);
  </code></pre>
  
  <p>Now when I do something like this, the second user will send a message but it will come from the SAME mailbox as user1 (i.e. both messages will come from dummy-email@gmail.com).</p>
  
  <p>Can somebody explain to me why this is happening? Do I have to close the connection somehow? How can I send the two emails and have them come from the different accounts? Please help me.</p>
  
  <p>Here is my code which actually sends the email connecting to the user's gmail account.</p>
  
  <pre><code>public void sendMail(String toAddress, String subject, String body){     
      Properties props = new Properties();
      props.put("mail.smtp.host", "smtp.gmail.com");
      props.put("mail.smtp.socketFactory.port", "465");
      props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
      props.put("mail.smtp.auth", "true");
      props.put("mail.smtp.port", "465");
  
      Session session = Session.getDefaultInstance(props,
          new javax.mail.Authenticator() 
          {
              protected PasswordAuthentication getPasswordAuthentication()
              { return new PasswordAuthentication(getUsername(),getPassword());   }
          });     
  
          try {
              Message message = new MimeMessage(session);
              message.setFrom(new InternetAddress(getUsername()));
              message.setRecipients(Message.RecipientType.TO, 
                  InternetAddress.parse(toAddress));
              message.setSubject(subject);
              message.setContent(body, "text/html");
  
              Transport.send(message);
  
  
              } catch (MessagingException e) {
                  throw new RuntimeException(e);
              }           
      }
  </code></pre>