[英]Sending emails with any kind of attachments
我想添加一個附件(無論是鏈接,圖像,視頻還是其他任何內容)以及我通過電子郵件發送的文本。 直到現在,我只能將純文本作為電子郵件發送。 如何添加附件?
這是我在工作線程中發送電子郵件進程的代碼:
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();
編輯:正如所建議的,我已經研究過[ 使用JavaMail API在Android中發送電子郵件而不使用默認/內置應用程序 。 但沒有任何關於在解決方案中添加附件的文章。
修復所有這些常見的JavaMail錯誤 。 確保您使用的是JavaMail for Android 。 有關如何使用附件發送消息,請參閱JavaMail FAQ。 例如,請參閱sendfile.java示例程序 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.