Android发送邮件代码
时间: 2023-11-03 15:28:15 浏览: 40
以下是一个发送邮件的基本代码示例,你需要在代码中填写你的邮箱地址和密码,以及收件人、主题和内容等信息:
```java
public void sendEmail() {
String email = "yourEmail@gmail.com";
String password = "yourPassword";
String recipient = "recipientEmail@gmail.com";
String subject = "Test Email";
String message = "This is a test email from Android.";
String[] recipients = {recipient};
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("message/rfc822");
intent.putExtra(Intent.EXTRA_EMAIL, recipients);
intent.putExtra(Intent.EXTRA_SUBJECT, subject);
intent.putExtra(Intent.EXTRA_TEXT, message);
try {
// Authenticate with your Gmail account
Authenticator auth = new Authenticator() {
// Override the getPasswordAuthentication method
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(email, password);
}
};
// Create a new session with Gmail SMTP server
Session session = Session.getInstance(getProperties(), auth);
// Send email using the created session
Transport.send(new Message(session, recipients, subject, message));
Toast.makeText(this, "Email sent successfully", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, "Failed to send email", Toast.LENGTH_SHORT).show();
}
}
private Properties getProperties() {
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
return props;
}
```
注意:在使用此代码之前,请确保已经在你的 Android 项目中添加了邮件发送相关的依赖库。