2016-05-31 6 views
-4
//configuration 

    private String mailhost = "smtp.gmail.com"; 
    private String user; 
    private String password; 
    private Session session; 

    // constructor 
    public GmailSender(String user, String password) { 
     this.user = user; 
     this.password = password; 
     Properties props = new Properties(); 
     props.setProperty("mail.transport.protocol", "smtp"); 
     props.setProperty("mail.host", mailhost); 
     props.put("mail.smtp.auth", "true"); 
     props.put("mail.smtp.port", "465"); 
     props.put("mail.smtp.socketFactory.port", "465"); 
     props.put("mail.smtp.user", user); 
     props.put("mail.smtp.password", password); 
     props.put("mail.smtp.socketFactory.fallback", "false"); 
     props.setProperty("mail.smtp.quitwait", "false"); 
     session = Session.getInstance(props, this); 
    } 

    protected PasswordAuthentication getPasswordAuthentication() { 
     return new PasswordAuthentication(user, password); 
    } 

    // method to send mail 
    public synchronized void sendMail(String subject, String body, String sender, String recipients, String cc) 
      throws Exception { 
     try { 
      int i = 0; 
      Address[] ccAddress = new Address[] {}; 
      MimeMessage message = new MimeMessage(session); 
      DataHandler handler = new DataHandler(new ByteArrayDataSource(body.getBytes(), "text/plain")); 
      message.setSender(new InternetAddress(sender)); 
      message.setSubject(subject); 
      message.setDataHandler(handler); 
      message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients)); 

      if (cc != null && !cc.isEmpty()) { 
       String[] addressArray = cc.split(","); 
       ccAddress = new Address[addressArray.length + 2]; 
       for (int j = 0; j < addressArray.length; j++) { 
        ccAddress[j] = new InternetAddress(addressArray[j]); 
       } 

       i = addressArray.length; 

      } 
      if (i != 0) { 

       // i=i+2; 
       ccAddress[i] = new InternetAddress(sender); 
       ccAddress[i + 1] = new InternetAddress(sender); 

      } 

      if (i == 0) { 
       i = 2; 
       ccAddress = new Address[1]; 
       ccAddress[0] = new InternetAddress(sender); 

      message.addRecipients(Message.RecipientType.CC, ccAddress); 
      Transport.send(message); 
     } catch (Exception e) { 
      e.getMessage(); 

      throw new Exception(); 
     } 

Antwort

3

Hallo, wenn Sie gmail für Sende Mail verwenden Sie die Sicherheit Ihres Google Mail-Konto ändern müssen gehen durch diesen Link gelangen Sie link

Change Security

helfen
+0

gleiche getan worden, aber gleiche Ausnahme –

+0

kommt auf Aus –

+0

@ritikabhardwaj @ritikabhardwaj Set gibt es eine Beschränkung auf smtp bei Ihrer Entwicklung envirenment –

Verwandte Themen