我尝试通过电子邮件意图中的附件发送图像。我选择Gmail应用程序,似乎文件已附加,但是当我单击在gmail应用程序上发送时,它说:
不幸的是,Gmail已经停止了。
请帮助我是什么问题以及如何解决它?
AndroidManifest.xml:
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
我的活动.java:
public class MyActivity extends Activity {
private static final int SELECT_PICTURE = 1;
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 2;
private String selectedImagePath;
TextView uritv=null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
uritv = (TextView) findViewById(R.id.uritxt);
Button send = (Button) findViewById(R.id.sendBtn);
send.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (uritv.getText().toString().equals("URI")) {
Toast.makeText(getApplicationContext(),"Please choose an image first!",Toast.LENGTH_SHORT).show();
} else {
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.setType("image/*");
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{"myemail@myemail.com"});
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,"Test Subject");
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, "From My App");
emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(uritv.getText().toString()));
startActivity(Intent.createChooser(emailIntent, "Send mail..."));
}
}
});
Button galbtn = (Button) findViewById(R.id.galBtn);
galbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
"Select Picture"), SELECT_PICTURE);
}
});
Button cambtn = (Button) findViewById(R.id.camBtn);
cambtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE || requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
uritv.setText(selectedImagePath.toString());
}
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
}
它需要互联网权限,请在清单文件中添加此权限
<uses-permission android:name="android.permission.INTERNET"/>
是的,问题出在您为获取文件路径而构建的 URI 上。 您正在采用原始文件路径,而 URI 并非如此。 它应该是像下面一样
content://media/external/images/media
请检查您的路径并再次测试
我做了一些更改,我可以成功发送邮件。由于您使用的是Gmail,因此请使用GmailSender Class。喜欢这个
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.Security;
import java.util.List;
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.MessagingException;
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;
import android.net.Uri;
public class GMailSender extends javax.mail.Authenticator {
private String mailhost = "smtp.gmail.com";
private String user;
private String password;
private Session session;
String ContentType = "";
static {
Security.addProvider(new JSSEProvider());
}
public GMailSender(String user, String password) {
this.user = user;
this.password = password;
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.host", mailhost);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.quitwait", "false");
session = Session.getDefaultInstance(props, this);
}
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password);
}
public synchronized void sendMail(String subject, String body,
String sender, String recipients, List<Uri> uriList)
throws Exception {
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(user));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(
recipients));
message.setSubject(subject);
// 3) create MimeBodyPart object and set your message content
BodyPart messageBodyPart1 = new MimeBodyPart();
messageBodyPart1.setText(body);
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart1);
for (int i = 0; i < uriList.size(); i++) {
// 4) create new MimeBodyPart object and set DataHandler object
// to this object
MimeBodyPart messageBodyPart2 = new MimeBodyPart();
String filename = uriList
.get(i)
.getPath()
.substring(
uriList.get(i).getPath().lastIndexOf("/") + 1,
uriList.get(i).getPath().length());// change
// accordingly
System.out.println("filename " + filename);
DataSource source = new FileDataSource(uriList.get(i).getPath());
messageBodyPart2.setDataHandler(new DataHandler(source));
messageBodyPart2.setFileName(filename);
// 5) create Multipart object and add MimeBodyPart objects to
// this object
multipart.addBodyPart(messageBodyPart2);
}
// 6) set the multiplart object to the message object
message.setContent(multipart);
// 7) send message
Transport.send(message);
System.out.println("message sent....");
} catch (MessagingException ex) {
ex.printStackTrace();
}
}
}
最好将邮件发送保留在异步任务或线程中。并在您的发送按钮中调用它。
class SaveAsyncTask extends AsyncTask<Void, Integer, Boolean> {
private ProgressDialog progressDialogue;
private Boolean status = false;
@Override
protected Boolean doInBackground(Void... arg0) {
try {
ArrayList<Uri> uList = new ArrayList<Uri>();
u.add(Uri.parse(uritv.getText().toString()));
try {
GMailSender sender = new GMailSender("<Sender Mail>",
"<Sender Password>");
Log.d("TAG: ", "Mail SENT");
sender.sendMail("Subject Text", "Body Text", "<Sender Mail>", "<Recipient Mail>", uList);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return status;
} catch (Exception e) {
e.printStackTrace();
return Boolean.FALSE;
}
}
protected void onPreExecute() {
progressDialogue = ProgressDialog.show(MainActivity.this,
"Sending Mail...",
"Please Wait..", true,
false);
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(Boolean result) {
// result is the value returned from doInBackground
progressDialogue.dismiss();
}
}