Я новичок в программировании Android и Android Studio. Я разрабатываю простое приложение для Android, которое может отправлять электронные письма с вложениями.Я уже могу отправить электронное письмо, но у меня проблемы с приложением.Когда я добавляю mimebodypart для вложения, я не могу сейчас получать электронные письма.Вот мой код
SimpleMail.java
package com.team8.javamail2;
import android.content.Context;
import android.os.Environment;
import java.io.File;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
/**
* Created by VEN on 1/27/2019.
*/
public class SimpleMail {
/**CHANGE ACCORDINGLY**/
private static final String SMTP_HOST_NAME = "smtp.gmail.com";
private static final String SMTP_AUTH_USER = "unvrsx@gmail.com";
private static final String SMTP_AUTH_PWD = "XXXXXXXXXX";
private static Message message;
private File file ;
private Context context;
public static void sendEmail(String to, String subject, String msg){
// Recipient's email ID needs to be mentioned.
// Sender's email ID needs to be mentioned
String from = "unvrsx@gmail.com"; //from
final String username = SMTP_AUTH_USER;
final String password = SMTP_AUTH_PWD;
// Assuming you are sending email through relay.jangosmtp.net
String host = SMTP_HOST_NAME;
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", "587");
// Get the Session object.
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
// Create a default MimeMessage object.
message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the header.
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));
// Set Subject: header field
message.setSubject(subject);
// Create the message part
BodyPart messageBodyPart = new MimeBodyPart();
// Now set the actual message
messageBodyPart.setContent(msg, "text/html");
// Create a multipar message
// Set text message part
// Part two is attachment
String filepath = "/storage/emulated/0/WaterMarkImages";
String filename = "Book.xlsx";
File att = new File(new File(filepath),filename);
MimeBodyPart messageBodyPart2 = new MimeBodyPart();
messageBodyPart2.attachFile(att);
DataSource source = new FileDataSource(att);
messageBodyPart2.setDataHandler(new DataHandler(source));
messageBodyPart2.setFileName(filename);
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
multipart.addBodyPart(messageBodyPart2);
// Send the complete message partBidt
message.setContent(multipart);
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
MainActivity.java
package com.team8.javamail2;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.File;
public class MainActivity extends AppCompatActivity {
private EditText toEmailEditText;
private EditText subjectEditText;
private EditText messageEditText;
private Button sendButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toEmailEditText = (EditText) findViewById(R.id.editTextEmail);
subjectEditText = (EditText) findViewById(R.id.editTextSubject);
messageEditText = (EditText) findViewById(R.id.editTextMessage);
sendButton = (Button) findViewById(R.id.buttonSend);
sendButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
String to = toEmailEditText.getText().toString().trim();
String subject = subjectEditText.getText().toString();
String message = messageEditText.getText().toString();
if(to.isEmpty()){
Toast.makeText(MainActivity.this, "You must enter a recipient email", Toast.LENGTH_LONG).show();
}else if(subject.isEmpty()){
Toast.makeText(MainActivity.this, "You must enter a Subject", Toast.LENGTH_LONG).show();
}else if(message.isEmpty()){
Toast.makeText(MainActivity.this, "You must enter a message", Toast.LENGTH_LONG).show();
}else {
//everything is filled out
//send email
new SimpleMail().sendEmail(to, subject, message);
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.team8.javamail2">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Я не знаю, если что-то здесь вызывает проблему
String filepath = "/storage/emulated/0/WaterMarkImages";
String filename = "Book.xlsx";
File att = new File(new File(filepath),filename);
MimeBodyPart messageBodyPart2 = new MimeBodyPart();
messageBodyPart2.attachFile(att);
DataSource source = new FileDataSource(att);
messageBodyPart2.setDataHandler(new DataHandler(source));
messageBodyPart2.setFileName(filename);
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
multipart.addBodyPart(messageBodyPart2);