title: Mail Authentication through Java
body: <p>I am building an application that takes in the username and password from the user and helps to send mails, using Java to code the same. I am using the Authenticator class from JavaMail API to get the authentication done. I am using this code-</p>
  
  <pre><code> import java.util.Date;
   import java.util.Properties;
   import javax.mail.Authenticator;
   import javax.mail.Message;
   import javax.mail.MessagingException;
   import javax.mail.PasswordAuthentication;
   import javax.mail.Session;
   import javax.mail.Transport;
   import javax.mail.internet.InternetAddress;
   import javax.mail.internet.MimeMessage;
  
   public class MailSender{
  
      GUI input = new GUI();
      String username2= input.username.getText();
      String password2 = input.password.getText();
  
      public void SendMail(String ToAddress, String Name, String username1, String password1, String subject, String message, String salutation) {
  
          String host = "smtp.gmail.com";
          String from = "xxxx@xxxx.com";
          String to = ToAddress;
  
  
          Properties props = new Properties();
          props.put("mail.smtp.host", host);
          props.put("mail.smtp.port", 25);
          props.put("mail.debug", "true");
          props.put("mail.transport.protocol", "smtp");
          props.put("mail.smtp.auth", "true");
          props.put("mail.smtp.starttls.enable", "true");
  
  
          Session session = Session.getInstance(props, new GMailAuthenticator());
  
          try {
  
  
              Message msg = new MimeMessage(session);
  
  
              msg.setFrom(new InternetAddress(from));
  
              InternetAddress[] address = {new InternetAddress(to)};
              msg.setRecipients(Message.RecipientType.TO, address);
  
  
              msg.setSubject(subject);
              msg.setSentDate(new Date());
  
  
              msg.setText(salutation+" "+Name+","+ "\n"+ message);
  
  
              Transport.send(msg);
  
          }
          catch (MessagingException mex) {
              mex.printStackTrace();
          }
  
      }
  
      private static class GMailAuthenticator extends Authenticator {
          @Override
          protected PasswordAuthentication getPasswordAuthentication() {
              return new PasswordAuthentication(username2, password2);
          }
      }
  </code></pre>
  
  <p>}</p>
  
  <p>I have created a GUI class that takes in the username, password, subject, mail text as user input, which I was stating earlier in the code itself. Netbeans shows an error in GmailAuthentication class that a "non-static variable (like username2 and password2 here) can't be referenced from a static context."</p>
  
  <p>How can I get around this issue? I need to take the username and password as user input from the GUI class and use them to authenticate for Gmail.</p>