我能够发送电子邮件,只是附件左边.. 首先我拍照,我想把这张照片作为附件发送。 请帮忙
这是我的代码
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Properties;
import javax.mail.Authenticator;
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;
/**
* A simple {@link Fragment} subclass.
*/
public class ReportFragment extends Fragment implements View.OnClickListener, AdapterView.OnItemSelectedListener {
View view;
Button sendBtn;
public String s="Report sent";
int count=0;
Session session = null;
ProgressDialog pdialog = null;
Context context = null;
EditText reciep, sub, msg,user,pass;
TextView check;
public String uname,password,rec, subject, textMessage;
String[] items={"Police","Hospital","Fire-Station"};
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 1888;
Button cameraBtn;
ImageView imageView;
Spinner spin;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view=inflater.inflate(R.layout.fragment_report, container, false);
context = getActivity();
spin = (Spinner) view.findViewById(R.id.spinnerCategory);
sub = (EditText) view.findViewById(R.id.editTextSubject);
msg = (EditText) view.findViewById(R.id.editTextEmail);
pass = (EditText) view.findViewById(R.id.password);
cameraBtn = (Button) view.findViewById(R.id.cameraButton);
imageView = (ImageView) view.findViewById(R.id.imageView);
cameraBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent,
CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
});
spin.setOnItemSelectedListener(this);
ArrayAdapter<String> aa= new ArrayAdapter<String>(getActivity(),android.R.layout.simple_spinner_item,items);
aa.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
spin.setAdapter(aa);
sendBtn= (Button) view.findViewById(R.id.sendBtn);
sendBtn.setOnClickListener(this);
return view;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) {
Bitmap bmp = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
// convert byte array to Bitmap
Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray, 0,
byteArray.length);
imageView.setImageBitmap(bitmap);
}
}
}
public boolean isOnline()
{
ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
return networkInfo != null && networkInfo.isConnectedOrConnecting();
}
@Override
public void onClick(View v) {
if(!isOnline()) {
Toast.makeText(getActivity(),"No Internet connection",Toast.LENGTH_SHORT).show();
}
else if(sub.getText().length()==0)
{
Toast.makeText(getActivity(),"Subject cannot be empty",Toast.LENGTH_SHORT).show();
}
else if(msg.getText().length()<10)
{
Toast.makeText(getActivity(),"Please enter atleast 10 characters in Message",Toast.LENGTH_SHORT).show();
}
else if(pass.getText().length()==0)
{
Toast.makeText(getActivity(),"Please enter password",Toast.LENGTH_SHORT).show();
}
else
{
MainActivity activity = (MainActivity) getActivity();
String emailData = activity.getEmail();
uname = emailData;
//uname = user.getText().toString();
password = pass.getText().toString();
//rec = reciep.getText().toString();
// rec ="amey.palkar1@gmail.com";
subject = sub.getText().toString();
textMessage = msg.getText().toString();
Properties props = new Properties();
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");
Authenticator a = null;
a = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(uname, password);
}
};
session = Session.getDefaultInstance(props, a);
pdialog = ProgressDialog.show(context, "", "Sending Mail...", true);
RetreiveFeedTask task = new RetreiveFeedTask();
task.execute();
}
}
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
if(items[i].equals("Police"))
{
rec="police.goodsamaritan@gmail.com";
}
else if(items[i].equals("Hospital"))
{
rec="hospitasl.goodsamaritan@gmail.com";
}
else if(items[i].equals("Fire-Station"))
{
rec="fire.goodsamaritan@gmail.com";
}
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
class RetreiveFeedTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
try
{
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(uname));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(rec));
message.setSubject(subject);
message.setContent(textMessage, "text/html; charset=utf-8");
Transport.send(message);
} catch(MessagingException e) {
s="Username Password is wrong";
count=100;
} catch(Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result) {
pdialog.dismiss();
Toast.makeText(getActivity().getApplicationContext(), s, Toast.LENGTH_LONG).show();
s="Report Sent";
count=0;
}
}
}
这是我的代码 请帮助我有人如何在此代码中添加附件
答案 0 :(得分:1)
使用以下内容构建消息正文:
Multipart multipart = new MimeMultipart("related");
MimeBodyPart htmlPart = new MimeBodyPart();
// messageBody contains html that references image
// using something like <img src="cid:XXX"> where
// "XXX" is an identifier that you make up to refer
// to the image
htmlPart.setText(messageBody, "utf-8", "html");
multipart.addBodyPart(htmlPart);
MimeBodyPart imgPart = new MimeBodyPart();
// imageFile is the file containing the image
imgPart.attachFile(imageFile);
// or, if the image is in a byte array in memory, use
// imgPart.setDataHandler(new DataHandler(
// new ByteArrayDataSource(bytes, "image/whatever")));
// "XXX" below matches "XXX" above in html code
imgPart.setContentID("<XXX>");
multipart.addBodyPart(imgPart);
message.setContent(multipart);
此外,您还要修复其他common JavaMail mistakes。