我想添加一个附件(无论是链接,图像,视频还是其他),以及通过电子邮件发送的文本。到目前为止,我只能将纯文本作为电子邮件发送。如何添加附件?
这是我的用于在工作线程中发送电子邮件过程的代码:
public class GMailSender extends AsyncTask<Void,Void,Void> {
//Declaring Variables
private Context context;
private Session session;
//Information to send email
private String email;
private String subject;
private String msg;
//Progressdialog to show while sending email
//Class Constructor
public GMailSender(Context context, String email, String subject, String msg){
if (rb1 != null && rad.isChecked()){
message=s1;
}else if(rb1 != null && rad1.isChecked())
{
message=item;
}
//Initializing variables
this.context = context;
this.email = s4;
this.subject = s3;
this.msg = message;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
//Showing progress dialog while sending email
// progressDialog = ProgressDialog.show(context,"Sending message","Please wait...",false,false);
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
//Dismissing the progress dialog
//Showing a success message
Toast.makeText(context,"Message Sent",Toast.LENGTH_SHORT).show();
}
@Override
protected Void doInBackground(Void... params) {
//Creating properties
Properties props = new Properties();
//Configuring properties for gmail
//If you are not using gmail you may need to change the values
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
//Creating a new session
session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
//Authenticating the password
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(Smscreator.EMAIL, Smscreator.PASSWORD);
}
});
try {
//Creating MimeMessage object
MimeMessage mm = new MimeMessage(session);
//Setting sender address
mm.setFrom(new InternetAddress(Smscreator.EMAIL));
//Adding receiver
mm.addRecipient(Message.RecipientType.TO, new InternetAddress(email));
//Adding subject
mm.setSubject(subject);
//Adding message
mm.setText(msg);
//Sending email
Transport.send(mm);
} catch (MessagingException e) {
e.printStackTrace();
}
return null;
}
}
这是发送邮件的代码:
GMailSender sm = new GMailSender(context, s4, s3, message);
sm.execute();
Toast.makeText(context, "Email sent :)",
Toast.LENGTH_SHORT).show();
编辑:根据建议,我研究了[Sending Email in Android using JavaMail API without using the default/built-in app。但是在解决方案中添加附件一事无成。
答案 0 :(得分:0)
修复所有这些common JavaMail mistakes。确保您使用的是JavaMail for Android。并参阅how to send a message with an attachment的JavaMail常见问题解答。例如,请参见sendfile.java sample program。