Android 我想发送一封带有图像附件的电子邮件(javamail)
我可以发送电子邮件,只剩下附件部分。。 首先我正在拍照,我想把照片作为附件发送。 请帮忙 这是我的密码Android 我想发送一封带有图像附件的电子邮件(javamail),android,image,jakarta-mail,attachment,Android,Image,Jakarta Mail,Attachment,我可以发送电子邮件,只剩下附件部分。。 首先我正在拍照,我想把照片作为附件发送。 请帮忙 这是我的密码 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.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;
}
}
}
导入android.app.Activity;
导入android.app.ProgressDialog;
导入android.content.Context;
导入android.content.Intent;
导入android.graphics.Bitmap;
导入android.graphics.BitmapFactory;
导入android.net.ConnectivityManager;
导入android.net.NetworkInfo;
导入android.os.AsyncTask;
导入android.os.Bundle;
导入android.provider.MediaStore;
导入android.support.annotation.Nullable;
导入android.support.v4.app.Fragment;
导入android.view.LayoutInflater;
导入android.view.view;
导入android.view.ViewGroup;
导入android.widget.AdapterView;
导入android.widget.ArrayAdapter;
导入android.widget.Button;
导入android.widget.EditText;
导入android.widget.ImageView;
导入android.widget.Spinner;
导入android.widget.TextView;
导入android.widget.Toast;
导入java.io.ByteArrayOutputStream;
导入java.io.IOException;
导入java.util.Properties;
导入javax.mail.Authenticator;
导入javax.mail.Message;
导入javax.mail.MessaginException;
导入javax.mail.Multipart;
导入javax.mail.PasswordAuthentication;
导入javax.mail.Session;
导入javax.mail.Transport;
导入javax.mail.internet.InternetAddress;
导入javax.mail.internet.MimeBodyPart;
导入javax.mail.internet.mimessage;
导入javax.mail.internet.MimeMultipart;
/**
*一个简单的{@link Fragment}子类。
*/
公共类ReportFragment扩展片段实现View.OnClickListener、AdapterView.OnItemSelectedListener{
视图;
按钮sendBtn;
公共字符串s=“已发送报告”;
整数计数=0;
会话=空;
ProgressDialog pdialog=null;
Context=null;
EditText接收、订阅、消息、用户、通过;
文本视图检查;
公共字符串uname、password、rec、subject、textMessage;
字符串[]项={“警察”、“医院”、“消防局”};
私有静态最终整数捕获\图像\活动\请求\代码=1888;
按钮摄像机;
图像视图图像视图;
旋转器旋转;
@可空
@凌驾
CreateView上的公共视图(布局、充气机、视图组容器、捆绑包保存状态){
视图=充气机。充气(R.layout.fragment_报告,容器,错误);
context=getActivity();
spin=(微调器)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=(按钮)view.findViewById(R.id.cameraButton);
imageView=(imageView)view.findViewById(R.id.imageView);
cameraBtn.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图){
意向意向=新意向(MediaStore.ACTION\u IMAGE\u CAPTURE);
startActivityForResult(意向,
捕获(图像、活动、请求、代码);
}
});
spin.setOnItemSelectedListener(此);
ArrayAdapter aa=新的ArrayAdapter(getActivity(),android.R.layout.simple\u微调器\u项,项);
aa.setDropDownViewResource(android.R.layout.simple\u dropdown\u item\u 1line);
旋转适配器(aa);
sendBtn=(按钮)view.findViewById(R.id.sendBtn);
sendBtn.setOnClickListener(此);
返回视图;
}
@凌驾
ActivityResult上的公共void(int请求代码、int结果代码、意图数据){
if(requestCode==捕获\图像\活动\请求\代码){
if(resultCode==Activity.RESULT\u确定){
位图bmp=(位图)data.getExtras().get(“数据”);
ByteArrayOutputStream=新建ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG,100,流);
byte[]byteArray=stream.toByteArray();
//将字节数组转换为位图
位图位图=位图工厂。解码字节数组(字节数组,0,
byteArray.长度);
设置图像位图(位图);
}
}
}
公共布尔isOnline()
{
ConnectivityManager cm=(ConnectivityManager)getActivity().getSystemService(Context.CONNECTIVITY_服务);
NetworkInfo NetworkInfo=cm.getActiveNetworkInfo();
返回networkInfo!=null&&networkInfo.isConnectedOrConnecting();
}
@凌驾
公共void onClick(视图v){
如果(!isOnline()){
Toast.makeText(getActivity(),“无Internet连接”,Toast.LENGTH_SHORT.show();
}
else if(sub.getText().length()==0)
{
Toast.makeText(getActivity(),“主题不能为空”,Toast.LENGTH_SHORT.show();
}
else if(msg.getText().length()adapterView){
}
类RetreiveFeedTask扩展了AsyncTask{
@凌驾
受保护的字符串doInBackground(字符串…参数){
尝试
{
Message Message=新的mimessage(会话);
message.setFrom(新因特网地址(uname));
message.setRecipients(message.RecipientType.TO,InternetAddress.parse(rec));
message.setSubject(主题);
setContent(textMessage,“text/html;charset=utf-8”);
传输。发送(消息);
}捕获(消息异常e){
s=“用户名密码错误”;
计数=100;
}捕获(例外e){
e、 printStackTrace();
}
返回null;
}
@凌驾
受保护的void onPostExecute(字符串结果){
pdialog.disclose();
Toast.makeText(getActivity().getApplicationContext(),s,Toast.LENGTH_LONG.show();
s=“已发送报告”;
计数=0;
}
}
}
这是我的密码
请帮助我了解如何在此代码中添加附件使用类似以下内容来构建邮件正文:
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);
Multipart Multipart=新的MimeMultipart(“相关”);
MimeBodyPart htmlPart=新的MimeBodyPart();
//messageBody包含引用i的html