我已阅读此处链接的问题。例如,当用户按下按钮时,我已经尝试过这种方法以编程方式发送电子邮件。
它确实适用于 2.3.7 版本的 Android。
问题是当尝试在更新的 Android 版本(如 4.1.2)上启动应用程序时,它什么也没做。在这些设备上会出现 toast,但不会发送电子邮件。
所以,我尝试了这段代码,但它也不起作用。
...
sendButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
//Read EditText
EditText text = (EditText)findViewById(R.id.editText1);
String my_mail = text.getText().toString().toLowerCase();
if (my_mail.matches("")){
Toast toast = Toast.makeText(context, "Please insert a valid email address!", Toast.LENGTH_LONG);
toast.show();
}
//send mail
try {
WebSendMail(my_mail);
Toast toast = Toast.makeText(context, "Email sent!", Toast.LENGTH_LONG);
toast.show();
} catch (Exception e) {
Log.e("SendMail", e.getMessage(), e);
}
}
});
public static boolean WebSendMail(String mail){
//email sender parameter
String smtpHost = "smtp.gmail.com";
String addressFrom = "account@gmail.com";
String login = addressFrom;
String password = "password";
String subject = "Subject!";
String message = "html code";
try {
Properties props = new Properties();
props.setProperty("mail.host", smtpHost);
props.setProperty("mail.smtp.port", "587");
props.setProperty("mail.smtp.auth", "true");
props.setProperty("mail.smtp.starttls.enable", "true");
Authenticator auth = new SMTPAuthenticator(login, password);
Session session = Session.getInstance(props, auth);
MimeMessage msg = new MimeMessage(session);
msg.setText(message);
msg.setSubject(subject);
msg.setContent(message, "text/html");
msg.setFrom(new InternetAddress(addressFrom));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(mail));
Transport.send(msg);
return true;
} catch (Exception ex) {
return false;
}
}
有什么帮助吗?