我通过smtp发送电子邮件,但只收到文件或附件,而不是电子邮件和主题的正文。谁能告诉我问题出在哪里?
public class SendMail扩展了AppCompatActivity {
EditText edt_subject,edt_body,edt_choosenFile;
private Button sendEmail;
private Button chooseFileButton;
private String filename;
String uniqueId,subject,mailbody;
private static final int REQUEST_CHOOSER = 1234;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_send_mail);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
edt_subject=(EditText)findViewById(R.id.et_Subject);
edt_body=(EditText)findViewById(R.id.et_mail_body);
subject=edt_subject.getText().toString();
mailbody=edt_body.getText().toString();
sendEmail = (Button) findViewById(R.id.send_email_button_id);
sendEmail.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Thread(new Runnable() {
@Override
public void run() {
try {
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");
Session session = Session.getInstance(props,
new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(
"sender@gmail.com","password");
}
});
// TODO Auto-generated method stub
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress("sender@gmail.com"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("receiver@gmail.com"));
message.setSubject(subject);
message.setText(mailbody);
if (filename!=null) {
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(mailbody);
Multipart _multipart = new MimeMultipart();
FileDataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
_multipart.addBodyPart(messageBodyPart);
message.setContent(_multipart);
}
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}).start();
}
});
chooseFileButton = (Button) findViewById(R.id.choose_file_button_id);
chooseFileButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Create the ACTION_GET_CONTENT Intent
Intent getContentIntent = FileUtils.createGetContentIntent();
Intent intent = Intent.createChooser(getContentIntent, "Select a file");
startActivityForResult(intent, REQUEST_CHOOSER);
}
});
}
答案 0 :(得分:0)
主体部分需要是多部分的第一个身体部位。您对message.setTetent的调用将被您对message.setContent的调用覆盖。 JavaMail sample programs中有很多例子。