无法通过电子邮件意图发送图像附件

Posted

技术标签:

【中文标题】无法通过电子邮件意图发送图像附件【英文标题】:Can't send image attachment by email intent 【发布时间】:2013-12-01 04:35:18 【问题描述】:

我试图通过电子邮件意图的附件发送图像。 我选择了 gmail 应用程序,似乎文件已附加,但是当我点击 gmail 应用程序上的发送时,它显示:

很遗憾,Gmail 已停止。

请帮我看看是什么问题,我该如何解决?

AndroidManifest.xml:

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

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

MyActivity.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);


【问题讨论】:

【参考方案1】:

我做了一些修改,我可以成功发送邮件。由于您使用的是 Gmail,因此请使用 GmailSender 类。像这样

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();
    


【讨论】:

【参考方案2】:

是的,问题在于您为获取文件路径而构建的 URI。您正在采用原始文件路径,而 URI 并非如此。它应该如下所示

content://media/external/images/media

请检查您的路径并再次测试

【讨论】:

是的!我的问题是我将 URI 转换为路径!我应该使用 URI。我已经删除了 getpath 方法,它已修复!【参考方案3】:

需要互联网权限,在清单文件中添加此权限

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

【讨论】:

以上是关于无法通过电子邮件意图发送图像附件的主要内容,如果未能解决你的问题,请参考以下文章

Python:多部分 html 电子邮件通过嵌入式图像和附件发送

在 iOS 中使用 Mandrill API 的电子邮件无法正常使用图像附件

如何使用 Qt 发送带有图像附件的电子邮件?

用于发送带有附件的电子邮件的 GMAIL API

通过电子邮件发送文件 - 无法使用附件 - Android

使用 android 意图将 html 文件作为电子邮件正文内容发送