我想不使用Gmail应用程序发送带有附件的电子邮件

时间:2018-11-06 09:18:46

标签: android

我尝试不使用Gmail应用程序自动发送带有附件的电子邮件。我收到了电子邮件,但没有收到电子邮件中的附件。这是我的代码。谁能帮我解决这个问题?

SendMailActivity.java

公共类SendMailActivity扩展了AppCompatActivity {     按钮发送;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button send = findViewById(R.id.button1);

    send.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            Log.i("SendMailActivity", "Send Button Clicked.");

            String fromEmail = "saip@gmail.com";
            String fromPassword = "******";
            String toEmails = "anu.p@gmail.com";
            List<String> toEmailList = Arrays.asList(toEmails
                    .split("\\s*,\\s*"));
            Log.i("SendMailActivity", "To List: " + toEmailList);
            String emailSubject = "hello";
            String emailBody = "hi everyone";

            new SendMailTask(SendMailActivity.this).execute(fromEmail,
                    fromPassword, toEmailList, emailSubject, emailBody);
        }
    });
}

}

GMail.java

公共类GMail {

final String emailPort = "587";// gmail's smtp port
final String smtpAuth = "true";
final String starttls = "true";
final String emailHost = "smtp.gmail.com";
String fromEmail;
String fromPassword;
List<String> toEmailList;
String emailSubject;
String emailBody;
Properties emailProperties;
Session mailSession;
MimeMessage emailMessage;
private Multipart _multipart = new MimeMultipart();

public GMail() {

}

public GMail(String fromEmail, String fromPassword,
             List<String> toEmailList, String emailSubject, String emailBody) {
    this.fromEmail = fromEmail;
    this.fromPassword = fromPassword;
    this.toEmailList = toEmailList;
    this.emailSubject = emailSubject;
    this.emailBody = emailBody;

    emailProperties = System.getProperties();
    emailProperties.put("mail.smtp.port", emailPort);
    emailProperties.put("mail.smtp.auth", smtpAuth);
    emailProperties.put("mail.smtp.starttls.enable", starttls);
    Log.i("GMail", "Mail server properties set.");
}

public MimeMessage createEmailMessage() throws AddressException,
        MessagingException, UnsupportedEncodingException {

    mailSession = Session.getDefaultInstance(emailProperties, null);
    emailMessage = new MimeMessage(mailSession);

    emailMessage.setFrom(new InternetAddress(fromEmail, fromEmail));
    for (String toEmail : toEmailList) {
        Log.i("GMail", "toEmail: " + toEmail);
        emailMessage.addRecipient(Message.RecipientType.TO,
                new InternetAddress(toEmail));
    }
    BodyPart messageBodyPart = new MimeBodyPart();
    messageBodyPart.setText("Here's the file");
    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(messageBodyPart);
    messageBodyPart = new MimeBodyPart();
    String filename = "storage/emulated/0/Pictures/Screenshots/Screenshot_test.png";
    DataSource source = new FileDataSource(filename);
    messageBodyPart.setDataHandler(new DataHandler(source));
    messageBodyPart.setFileName(filename);
    multipart.addBodyPart(messageBodyPart);
    emailMessage.setContent(multipart);
    emailMessage.setSubject(emailSubject);
    emailMessage.setContent(emailBody, "text/html");// for a html email
    emailMessage.setText(emailBody);// for a text email
    Log.i("GMail", "Email Message created.");
    return emailMessage;
}

public void sendEmail() throws AddressException, MessagingException {

    Transport transport = mailSession.getTransport("smtp");
    transport.connect(emailHost, fromEmail, fromPassword);
    Log.i("GMail", "allrecipients: " + emailMessage.getAllRecipients());
    transport.sendMessage(emailMessage, emailMessage.getAllRecipients());
    transport.close();
    Log.i("GMail", "Email sent successfully.");
}

}

SendMailTask​​

公共类SendMailTask​​扩展了AsyncTask {

private ProgressDialog statusDialog;
private Activity sendMailActivity;

public SendMailTask(Activity activity) {
    sendMailActivity = activity;

}

protected void onPreExecute() {
    statusDialog = new ProgressDialog(sendMailActivity);
    statusDialog.setMessage("Getting ready...");
    statusDialog.setIndeterminate(false);
    statusDialog.setCancelable(false);
    statusDialog.show();
}

@Override
protected Object doInBackground(Object... args) {
    try {
        Log.i("SendMailTask", "About to instantiate GMail...");
        publishProgress("Processing input....");
        GMail androidEmail = new GMail(args[0].toString(),
                args[1].toString(), (List) args[2], args[3].toString(),
                args[4].toString());
        publishProgress("Preparing mail message....");
        androidEmail.createEmailMessage();
        publishProgress("Sending email....");
        androidEmail.sendEmail();
        publishProgress("Email Sent.");
        Log.i("SendMailTask", "Mail Sent.");
    } catch (Exception e) {
        publishProgress(e.getMessage());
        Log.e("SendMailTask", e.getMessage(), e);
    }
    return null;
}

@Override
public void onProgressUpdate(Object... values) {
    statusDialog.setMessage(values[0].toString());

}

@Override
public void onPostExecute(Object result) {
    statusDialog.dismiss();
}

}

1 个答案:

答案 0 :(得分:0)

您可以使用this库轻松发送电子邮件

通过jitpack分级

 repositories {
        // ...
        maven { url "https://jitpack.io" }
 }

 dependencies {
            compile 'com.github.yesidlazaro:GmailBackground:1.2.0'
    }

权限

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>

对于附件,您需要在清单中设置 READ_EXTERNAL_STORAGE 权限

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

在您的活动中

    BackgroundMail.newBuilder(this)
            .withUsername("username@gmail.com")
            .withPassword("password12345")
            .withMailto("toemail@gmail.com")
            .withType(BackgroundMail.TYPE_PLAIN)
            .withSubject("this is the subject")
            .withBody("this is the body")
            .withAttachments(Environment.getExternalStorageDirectory().getPath() + "/test.txt")
            .withOnSuccessCallback(new BackgroundMail.OnSuccessCallback() {
                @Override
                public void onSuccess() {
                    //do some magic
                }
            })
            .withOnFailCallback(new BackgroundMail.OnFailCallback() {
                @Override
                public void onFail() {
                    //do some magic
                }
            })
            .send();