2017-07-09 211 views
2

所以我搜索了很多通過我的應用程序發送電子郵件,但沒有用戶必須登錄在電子郵件應用程序,併發送它自己。我想讓他把它寫在editText中,然後只需按下一個按鈕併發送給我。所以我就是這樣做的:2個郵件類的類,我的活動調用它,添加3個庫和互聯網許可。我做錯了什麼?通過應用程序發送電子郵件,而無需打開郵件在Android應用程序

這裏就是我所說的電子郵件程序:

private View.OnClickListener btnMode1Listener = new 
View.OnClickListener() { 
    @Override 
    public void onClick(View v) { 
     suggestionText = entre_suggestion.getText().toString(); 

     Log.i("SendMailActivity", "Send Button Clicked."); 

     String fromEmail = "[email protected]"; 
     String fromPassword = "frompassword"; 
     String toEmails = "[email protected]"; 
     List toEmailList = Arrays.asList(toEmails 
       .split("\\s*,\\s*")); 
     Log.i("SendMailActivity", "To List: " + toEmailList); 
     String emailSubject = "Suggestion"; 
     String emailBody = suggestionText; 
     new SendMailTask(suggestions.this).execute(fromEmail, 
       fromPassword, toEmailList, emailSubject, emailBody); 

    } 
}; 

這是第一課 「的GMail」:

public class GMail { 

final String emailPort = "587";// gmail's smtp port 
final String smtpAuth = "true"; 
final String starttls = "true"; 
final String emailHost = "smtp.gmail.com"; 

String fromEmail; 
String fromPassword; 
List toEmailList; 
String emailSubject; 
String emailBody; 

Properties emailProperties; 
Session mailSession; 
MimeMessage emailMessage; 

public GMail() { 

} 

public GMail(String fromEmail, String fromPassword, 
      List toEmailList, String emailSubject, String emailBody) { 
    this.fromEmail = fromEmail; 
    this.fromPassword = fromPassword; 
    this.toEmailList = toEmailList; 
    this.emailSubject = emailSubject; 
    this.emailBody = emailBody; 

    emailProperties = System.getProperties(); 
    emailProperties.put("mail.smtp.port", emailPort); 
    emailProperties.put("mail.smtp.auth", smtpAuth); 
    emailProperties.put("mail.smtp.starttls.enable", starttls); 
    Log.i("GMail", "Mail server properties set."); 
} 

public MimeMessage createEmailMessage() throws AddressException, 
     MessagingException, UnsupportedEncodingException { 

    mailSession = Session.getDefaultInstance(emailProperties, null); 
    emailMessage = new MimeMessage(mailSession); 

    emailMessage.setFrom(new InternetAddress(fromEmail, fromEmail)); 
    for (Object toEmail : toEmailList) { 
     Log.i("GMail","toEmail: "+toEmail); 
     emailMessage.addRecipient(Message.RecipientType.TO, 
       new InternetAddress((String) toEmail)); 
    } 

    emailMessage.setSubject(emailSubject); 
    emailMessage.setContent(emailBody, "text/html");// for a html email 
    // emailMessage.setText(emailBody);// for a text email 
    Log.i("GMail", "Email Message created."); 
    return emailMessage; 
} 

public void sendEmail() throws AddressException, MessagingException { 

    Transport transport = mailSession.getTransport("smtp"); 
    transport.connect(emailHost, fromEmail, fromPassword); 
    Log.i("GMail","allrecipients: "+emailMessage.getAllRecipients()); 
    transport.sendMessage(emailMessage, emailMessage.getAllRecipients()); 
    transport.close(); 
    Log.i("GMail", "Email sent successfully."); 
} 

} 

這是第二類 「SendMailtask」 :

public class SendMailTask extends AsyncTask { 

private ProgressDialog statusDialog; 
private Activity sendMailActivity; 

public SendMailTask(Activity activity) { 
    sendMailActivity = activity; 

} 

protected void onPreExecute() { 
    statusDialog = new ProgressDialog(sendMailActivity); 
    statusDialog.setMessage("Getting ready..."); 
    statusDialog.setIndeterminate(false); 
    statusDialog.setCancelable(false); 
    statusDialog.show(); 
} 

@Override 
protected Object doInBackground(Object... args) { 
    try { 
     Log.i("SendMailTask", "About to instantiate GMail..."); 
     publishProgress("Processing input...."); 
     GMail androidEmail = new GMail(args[0].toString(), 
       args[1].toString(), (List) args[2], args[3].toString(), 
       args[4].toString()); 
     publishProgress("Preparing mail message...."); 
     androidEmail.createEmailMessage(); 
     publishProgress("Sending email...."); 
     androidEmail.sendEmail(); 
     publishProgress("Email Sent."); 
     Log.i("SendMailTask", "Mail Sent."); 
    } catch (Exception e) { 
     publishProgress(e.getMessage()); 
     Log.e("SendMailTask", e.getMessage(), e); 
    } 
    return null; 
} 

@Override 
public void onProgressUpdate(Object... values) { 
    statusDialog.setMessage(values[0].toString()); 

} 

@Override 
public void onPostExecute(Object result) { 
    statusDialog.dismiss(); 
} 

} 

最後,3個librairies我說:

compile files('libs/activation.jar') 
compile files('libs/additionnal.jar') 
compile files('libs/mail.jar') 

所以,是的,我搜索了很多,並沒有找到如何調試它。我嘗試了很多不同的方式,但從未發送過電子郵件。我只想清楚,我不想打開郵件應用程序,我希望發送電子郵件而無需用戶執行某些操作。

+0

我想這也沒有工作和其他一些人...:https://stackoverflow.com/questions/2020088/發送電子郵件在Android的使用javamail的API無需使用默認內置的一個 –

回答

0

在您的帳戶設置,允許SMTP,並允許不安全的應用程序

0
package com.auto.smartautomates.smartautomates.Helpers; 

import com.crashlytics.android.Crashlytics; 

import java.util.Calendar; 
import java.util.Properties; 

import javax.mail.Authenticator; 
import javax.mail.Message; 
import javax.mail.MessagingException; 
import javax.mail.Multipart; 
import javax.mail.PasswordAuthentication; 
import javax.mail.Session; 
import javax.mail.internet.AddressException; 
import javax.mail.internet.InternetAddress; 
import javax.mail.internet.MimeBodyPart; 
import javax.mail.internet.MimeMultipart; 

/** 
* Created by sardar.khan on 6/8/2017. 
*/ 

public class MailService { 
    // public static final String MAIL_SERVER = "localhost"; 

    private String toList; 
    private String ccList; 
    private String bccList; 
    private String subject; 
    final private static String SMTP_SERVER = "smtp.gmail.com"; 
    private String from; 
    private String txtBody; 
    private String htmlBody; 
    private String replyToList; 
    private boolean authenticationRequired = false; 

    public MailService(String from, String toList, String subject, String txtBody, String htmlBody) { 
     this.txtBody = txtBody; 
     this.htmlBody = htmlBody; 
     this.subject = subject; 
     this.from = from; 
     this.toList = toList; 
     this.ccList = null; 
     this.bccList = null; 
     this.replyToList = null; 
     this.authenticationRequired = true; 


    } 


    public void sendAuthenticated() throws AddressException, MessagingException { 
     authenticationRequired = true; 
     send(); 
    } 

    /** 
    * Send an e-mail 
    * 
    * @throws MessagingException 
    * @throws AddressException 
    */ 
    public void send() throws AddressException, MessagingException { 
     Properties props = new Properties(); 

     // set the host smtp address 
     props.put("mail.smtp.host", SMTP_SERVER); 
     props.put("mail.user", from); 

     props.put("mail.smtp.starttls.enable", "true"); // needed for gmail 
     props.put("mail.smtp.auth", "true"); // needed for gmail 
     props.put("mail.smtp.port", "587"); // gmail smtp port 587 default gmail 

     /*Authenticator auth = new Authenticator() { 
      @Override 
      protected PasswordAuthentication getPasswordAuthentication() { 
       return new PasswordAuthentication("[email protected]", "mypassword"); 
      } 
     };*/ 


     Session session; 

     if (authenticationRequired) { 
      Authenticator auth = new SMTPAuthenticator(); 
      props.put("mail.smtp.auth", "true"); 
      session = Session.getDefaultInstance(props, auth); 
     } else { 
      session = Session.getDefaultInstance(props, null); 
     } 

     // get the default session 
     session.setDebug(true); 

     // create message 
     Message msg = new javax.mail.internet.MimeMessage(session); 

     // set from and to address 
     try { 
      msg.setFrom(new InternetAddress(from, from)); 
      msg.setReplyTo(new InternetAddress[]{new InternetAddress(from,from)}); 
     } catch (Exception e) { 
      Crashlytics.logException(e); 
      msg.setFrom(new InternetAddress(from)); 
      msg.setReplyTo(new InternetAddress[]{new InternetAddress(from)}); 
     } 

     // set send date 
     msg.setSentDate(Calendar.getInstance().getTime()); 

     // parse the recipients TO address 
     java.util.StringTokenizer st = new java.util.StringTokenizer(toList, ","); 
     int numberOfRecipients = st.countTokens(); 

     javax.mail.internet.InternetAddress[] addressTo = new javax.mail.internet.InternetAddress[numberOfRecipients]; 

     int i = 0; 
     while (st.hasMoreTokens()) { 
      addressTo[i++] = new javax.mail.internet.InternetAddress(st 
        .nextToken()); 
     } 
     msg.setRecipients(javax.mail.Message.RecipientType.TO, addressTo); 

     // parse the replyTo addresses 
     if (replyToList != null && !"".equals(replyToList)) { 
      st = new java.util.StringTokenizer(replyToList, ","); 
      int numberOfReplyTos = st.countTokens(); 
      javax.mail.internet.InternetAddress[] addressReplyTo = new javax.mail.internet.InternetAddress[numberOfReplyTos]; 
      i = 0; 
      while (st.hasMoreTokens()) { 
       addressReplyTo[i++] = new javax.mail.internet.InternetAddress(
         st.nextToken()); 
      } 
      msg.setReplyTo(addressReplyTo); 
     } 

     // parse the recipients CC address 
     if (ccList != null && !"".equals(ccList)) { 
      st = new java.util.StringTokenizer(ccList, ","); 
      int numberOfCCRecipients = st.countTokens(); 

      javax.mail.internet.InternetAddress[] addressCC = new javax.mail.internet.InternetAddress[numberOfCCRecipients]; 

      i = 0; 
      while (st.hasMoreTokens()) { 
       addressCC[i++] = new javax.mail.internet.InternetAddress(st 
         .nextToken()); 
      } 

      msg.setRecipients(javax.mail.Message.RecipientType.CC, addressCC); 
     } 

     // parse the recipients BCC address 
     if (bccList != null && !"".equals(bccList)) { 
      st = new java.util.StringTokenizer(bccList, ","); 
      int numberOfBCCRecipients = st.countTokens(); 

      javax.mail.internet.InternetAddress[] addressBCC = new javax.mail.internet.InternetAddress[numberOfBCCRecipients]; 

      i = 0; 
      while (st.hasMoreTokens()) { 
       addressBCC[i++] = new javax.mail.internet.InternetAddress(st 
         .nextToken()); 
      } 

      msg.setRecipients(javax.mail.Message.RecipientType.BCC, addressBCC); 
     } 

     // set header 
     msg.addHeader("X-Mailer", "MyAppMailer"); 
     msg.addHeader("Precedence", "bulk"); 
     // setting the subject and content type 
     msg.setSubject(subject); 

     Multipart mp = new MimeMultipart("related"); 

     // set body message 
     MimeBodyPart bodyMsg = new MimeBodyPart(); 
     bodyMsg.setText(txtBody, "iso-8859-1"); 
     bodyMsg.setContent(htmlBody, "text/html"); 
     mp.addBodyPart(bodyMsg); 
     msg.setContent(mp); 

     // send it 
     try { 
      javax.mail.Transport.send(msg); 
     } catch (Exception e) { 
      Crashlytics.logException(e); 
      e.printStackTrace(); 
     } 

    } 

    /** 
    * SimpleAuthenticator is used to do simple authentication when the SMTP 
    * server requires it. 
    */ 
    private static class SMTPAuthenticator extends javax.mail.Authenticator { 

     @Override 
     protected PasswordAuthentication getPasswordAuthentication() { 

      String username = "[email protected]"; 
      String password ="yourPassword"; 

      return new PasswordAuthentication(username, password); 
     } 
    } 

    public String getToList() { 
     return toList; 
    } 

    public void setToList(String toList) { 
     this.toList = toList; 
    } 

    public String getCcList() { 
     return ccList; 
    } 

    public void setCcList(String ccList) { 
     this.ccList = ccList; 
    } 

    public String getBccList() { 
     return bccList; 
    } 

    public void setBccList(String bccList) { 
     this.bccList = bccList; 
    } 

    public String getSubject() { 
     return subject; 
    } 

    public void setSubject(String subject) { 
     this.subject = subject; 
    } 

    public void setFrom(String from) { 
     this.from = from; 
    } 

    public void setTxtBody(String body) { 
     this.txtBody = body; 
    } 

    public void setHtmlBody(String body) { 
     this.htmlBody = body; 
    } 

    public String getReplyToList() { 
     return replyToList; 
    } 

    public void setReplyToList(String replyToList) { 
     this.replyToList = replyToList; 
    } 

    public boolean isAuthenticationRequired() { 
     return authenticationRequired; 
    } 

    public void setAuthenticationRequired(boolean authenticationRequired) { 
     this.authenticationRequired = authenticationRequired; 
    } 

} 
+0

嘗試使用此iam使用此代碼發送電子郵件。 –

+0

你可以參考這裏的鏈接.https://stackoverflow.com/questions/4345032/how-to-send-a-simple-email-programatically-exists-a-simple-way-to-do-it-it –

+0

希望你可以嘗試它,並得到它的工作謝謝。 –

相關問題