在Android中使用JavaMail API起草邮件需要以下步骤:
以下是一个示例代码:
import javax.mail.*;
import javax.mail.internet.*;
public class SendEmailActivity extends Activity {
private static final String EMAIL_HOST = "smtp.exmail.qq.com";
private static final String EMAIL_PORT = "465";
private static final String EMAIL_USERNAME = "your_email@example.com";
private static final String EMAIL_PASSWORD = "your_email_password";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_send_email);
Button sendButton = findViewById(R.id.send_button);
sendButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
sendEmail();
}
});
}
private void sendEmail() {
Properties props = new Properties();
props.put("mail.smtp.host", EMAIL_HOST);
props.put("mail.smtp.port", EMAIL_PORT);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.socketFactory.port", EMAIL_PORT);
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
Session session = Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(EMAIL_USERNAME, EMAIL_PASSWORD);
}
});
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(EMAIL_USERNAME));
message.addRecipient(Message.RecipientType.TO, new InternetAddress("recipient@example.com"));
message.setSubject("This is the subject of the email");
message.setText("This is the body of the email");
Transport.send(message);
Toast.makeText(getApplicationContext(), "Email sent successfully", Toast.LENGTH_SHORT).show();
} catch (MessagingException e) {
Toast.makeText(getApplicationContext(), "Failed to send email", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
}
请注意,为了使上述代码正常工作,你需要将"your_email@example.com"和"your_email_password"替换为你自己的邮箱地址和密码。此外,该示例仅仅是发送邮件的基本功能,你可以根据需求进行扩展和定制。
腾讯云的相关产品中,你可以使用"企业邮"提供的SMTP服务来发送邮件。具体腾讯云产品介绍和使用文档,请访问:腾讯企业邮 - SMTP服务。
领取专属 10元无门槛券
手把手带您无忧上云