我需要在没有用户输入的情况下自动发送带附件的电子邮件。我以前读过这两个答案。
Sending Email in Android using JavaMail API without using the default/built-in app
Android: Send e-mail with attachment automatically in the background
但是现在我没有收到任何电子邮件,我已经在gmail中启用了安全性较低的应用程序。这是我的代码:
public class Mail {
private String mailhost;
private String user;
private String password;
private Session session;
private String serverport;
public void main(String user, String password, String subject, String body){
sendFromGMail(user, password, subject,body);
}
private void sendFromGMail(String from, String pass, String subject, String body){
Properties props = System.getProperties();
String host = "smtp.gmail.com";
props.put("mail.smtp.ssl.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.user", from);
props.put("mail.smtp.password", pass);
props.put("mail.smtp.port", "465");
props.put("mail.smtp.auth", "true");
Session session = Session.getInstance(props);
MimeMessage message = new MimeMessage(session);
try {
InternetAddress adressTo = new InternetAddress(from);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, adressTo);
message.setSubject(subject);
message.setText(body);
Transport transport = session.getTransport("smtp");
transport.connect(host, from, pass);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
catch(MessagingException e){
Log.e("Not Sent", e.getMessage(), e);
}
}
}
这就是我使用它的方式:
try {
Mail mail = new Mail();
mail.main(gmailusername, gmailpassword, "Test", "Test2");
this.publishProgress("Email Sent");
}catch(Exception e){
Log.e("SendMail", e.getMessage(), e);
this.publishProgress("Email not sent");
}
编辑:我不想使用内置应用程序作为标题建议。只是想说清楚。
Java调试:
08-12 15:08:41.152 24062-24340/com.documax.cardreader I/System.out﹕ DEBUG: setDebug: JavaMail version 1.4.1
08-12 15:08:41.162 24062-24340/com.documax.cardreader I/System.out﹕ DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc.,1.4.1]
08-12 15:08:41.162 24062-24340/com.documax.cardreader I/System.out﹕ DEBUG SMTP: useEhlo true, useAuth true
08-12 15:08:41.162 24062-24340/com.documax.cardreader I/System.out﹕ DEBUG SMTP: trying to connect to host "smtp.gmail.com", port 465, isSSL false
答案 0 :(得分:1)
修复所有这些common mistakes,包括删除身份验证器。
在你的构造函数中删除对super()的调用,你不需要它。
另外,摆脱ByteArrayDataSource类。你不需要自己comes with JavaMail。另外,你的程序甚至没有使用它。
如果仍然无效,请使用新代码和新的失败详情更新帖子。