我试图在Android Studio中创建一个按钮,该按钮将所有信息放入EditText
字段中,然后将其作为电子邮件发送。
我使发送电子邮件的部分正常工作,但没有完成我想要的操作的按钮。
我制作了一个SendEmail
类,并添加了一个构造函数,该构造函数接受两个String值,我希望将它们作为电子邮件发送。我不知道如何将此类与包含参数的按钮集成在一起。
这就是我现在拥有的:
Button sendEmail = findViewById(R.id.button);
sendEmail.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
EditText test = (EditText) findViewById(R.id.editText);
String testText = test.getText().toString();
String textBody = "This is a test.";
}
});
我不确定从这里去哪里。有没有更好的方法来做我想做的事?
编辑:我希望Java发送电子邮件,而不是打开电子邮件应用程序并让用户手动发送电子邮件。我的电子邮件课程如下:
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class SendEmail {
public static void main(String [] args) {
// Recipient's email ID needs to be mentioned.
String to = "test@gmail.com";
// Sender's email ID needs to be mentioned
String from = "***@gmail.com";
// Get system properties
Properties properties = System.getProperties();
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true" );
properties.put("mail.smtp.host", "smtp.gmail.com");
properties.put("mail.smtp.port", 587);
Session session = Session.getDefaultInstance(properties, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from, "***");
}
});
try {
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the header.
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
// Set Subject: header field
message.setSubject("Subject Line test");
message.setText("This is a test for body of the e-mail.");
Transport.send(message);
System.out.println("Send message successfully");
} catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
此代码使我无需打开电子邮件客户端即可发送电子邮件。我试图弄清楚如何将此代码与按钮结合在一起。 另外,此SendEmail代码是我为测试而编写的代码,没有前面提到的构造函数。
答案 0 :(得分:-1)
尝试一下,希望它能正常工作-
Button sendEmail = findViewById(R.id.button);
sendEmail.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
EditText test = (EditText) findViewById(R.id.editText);
String subject = test.getText().toString();
String textBody = "This is a test.";
Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(
"mailto","email@email.com", null));
intent.putExtra(Intent.EXTRA_SUBJECT, subject);
intent.putExtra(Intent.EXTRA_TEXT, textBody);
startActivity(Intent.createChooser(intent, "Choose an Email client :"));
}
});