我成功地从应用程序传递了短信但无法邮寄图像。我想传递邮件以及函数内部的计时器活动内的图像 -
Thread background = new Thread() {
public void run() {
} }
1)MainActivity
public class MainActivity extends Activity {
ImageView image;
Activity context;
Preview preview;
Camera camera;
Button exitButton;
ImageView fotoButton;
LinearLayout progressLayout;
String path = "/sdcard/images/";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context=this;
fotoButton = (ImageView) findViewById(R.id.imageView_foto);
exitButton = (Button) findViewById(R.id.button_exit);
image = (ImageView) findViewById(R.id.imageView_photo);
progressLayout = (LinearLayout) findViewById(R.id.progress_layout);
preview = new Preview(this,
(SurfaceView) findViewById(R.id.KutCameraFragment));
FrameLayout frame = (FrameLayout) findViewById(R.id.preview);
frame.addView(preview);
preview.setKeepScreenOn(true);
Thread background = new Thread() {
public void run() {
try {
// Thread will sleep for 10 seconds
sleep(10*1000);
// After 10 seconds redirect to another intent
try {
takeFocusedPicture();
} catch (Exception e) {
}
exitButton.setClickable(false);
fotoButton.setClickable(false);
progressLayout.setVisibility(View.VISIBLE);
//Remove activity
// finish();
} catch (Exception e) {
}
}
};
// start thread
background.start();
fotoButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
takeFocusedPicture();
String fromEmail = "email_id@gmail.com";
String fromPassword = "xxxx";
String toEmails = "email_id@gmail.com";
String adminEmail = "email_id@gmail.com";
String emailSubject = "xxxx";
String adminSubject = "xxxx";
String emailBody = "xxxx";
String adminBody = "xxxx";
new SendMailTask(MainActivity.this).execute(fromEmail,
fromPassword, toEmails, emailSubject, emailBody,path);
} catch (Exception e) {
}
exitButton.setClickable(false);
fotoButton.setClickable(false);
progressLayout.setVisibility(View.VISIBLE);
}
});
}
@Override
protected void onResume() {
super.onResume();
// TODO Auto-generated method stub
if(camera==null){
camera = Camera.open();
camera.startPreview();
camera.setErrorCallback(new ErrorCallback() {
public void onError(int error, Camera mcamera) {
camera.release();
camera = Camera.open();
Log.d("Camera died", "error camera");
}
});
}
if (camera != null) {
if (Build.VERSION.SDK_INT >= 14)
setCameraDisplayOrientation(context,
CameraInfo.CAMERA_FACING_BACK, camera);
preview.setCamera(camera);
}
}
private void setCameraDisplayOrientation(Activity activity, int cameraId,
android.hardware.Camera camera) {
android.hardware.Camera.CameraInfo info = new android.hardware.Camera.CameraInfo();
android.hardware.Camera.getCameraInfo(cameraId, info);
int rotation = activity.getWindowManager().getDefaultDisplay()
.getRotation();
int degrees = 0;
switch (rotation) {
case Surface.ROTATION_0:
degrees = 0;
break;
case Surface.ROTATION_90:
degrees = 90;
break;
case Surface.ROTATION_180:
degrees = 180;
break;
case Surface.ROTATION_270:
degrees = 270;
break;
}
int result;
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
result = (info.orientation + degrees) % 360;
result = (360 - result) % 360; // compensate the mirror
} else { // back-facing
result = (info.orientation - degrees + 360) % 360;
}
camera.setDisplayOrientation(result);
}
Camera.AutoFocusCallback mAutoFocusCallback = new Camera.AutoFocusCallback() {
@Override
public void onAutoFocus(boolean success, Camera camera) {
try{
camera.takePicture(mShutterCallback, null, jpegCallback);
String fromEmail = "email_id@gmail.com";
String fromPassword = "xxxx";
String toEmails = "email_id@gmail.com";
String adminEmail = "email_id@gmail.com";
String emailSubject = "xxxx";
String adminSubject = "xxxx";
String emailBody = "xxxx";
String adminBody = "xxxx";
new SendMailTask(MainActivity.this).execute(fromEmail,
fromPassword, toEmails, emailSubject, emailBody,path);
}catch(Exception e){
}
}
};
Camera.ShutterCallback mShutterCallback = new ShutterCallback() {
@Override
public void onShutter() {
// TODO Auto-generated method stub
}
};
public void takeFocusedPicture() {
camera.autoFocus(mAutoFocusCallback);
}
PictureCallback rawCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
// Log.d(TAG, "onPictureTaken - raw");
}
};
PictureCallback jpegCallback = new PictureCallback() {
@SuppressWarnings("deprecation")
public void onPictureTaken(byte[] data, Camera camera) {
FileOutputStream outStream = null;
Calendar c = Calendar.getInstance();
File videoDirectory = new File(path);
if (!videoDirectory.exists()) {
videoDirectory.mkdirs();
}
try {
// Write to SD Card
outStream = new FileOutputStream(path + c.getTime().getSeconds() + ".jpg");
outStream.write(data);
outStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
Bitmap realImage;
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 5;
options.inPurgeable=true; //Tell to gc that whether it needs free memory, the Bitmap can be cleared
options.inInputShareable=true; //Which kind of reference will be used to recover the Bitmap data after being clear, when it will be used in the future
realImage = BitmapFactory.decodeByteArray(data,0,data.length,options);
ExifInterface exif = null;
try {
exif = new ExifInterface(path + c.getTime().getSeconds()
+ ".jpg");
//Toast.makeText(MainActivity.this,"You Clicked : " + exif,Toast.LENGTH_SHORT).show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
Log.d("EXIF value",
exif.getAttribute(ExifInterface.TAG_ORIENTATION));
if (exif.getAttribute(ExifInterface.TAG_ORIENTATION)
.equalsIgnoreCase("1")) {
realImage = rotate(realImage, 90);
} else if (exif.getAttribute(ExifInterface.TAG_ORIENTATION)
.equalsIgnoreCase("8")) {
realImage = rotate(realImage, 90);
} else if (exif.getAttribute(ExifInterface.TAG_ORIENTATION)
.equalsIgnoreCase("3")) {
realImage = rotate(realImage, 90);
} else if (exif.getAttribute(ExifInterface.TAG_ORIENTATION)
.equalsIgnoreCase("0")) {
realImage = rotate(realImage, 90);
}
} catch (Exception e) {
}
image.setImageBitmap(realImage);
fotoButton.setClickable(true);
camera.startPreview();
progressLayout.setVisibility(View.GONE);
exitButton.setClickable(true);
}
};
public static Bitmap rotate(Bitmap source, float angle) {
Matrix matrix = new Matrix();
matrix.postRotate(angle);
return Bitmap.createBitmap(source, 0, 0, source.getWidth(),
source.getHeight(), matrix, false);
}
}
2.)GMail.java
public class GMail {
final String emailPort = "587";// gmail's smtp port
final String smtpAuth = "true";
final String starttls = "true";
final String emailHost = "smtp.gmail.com";
String fromEmail;
String fromPassword;
@SuppressWarnings("rawtypes")
String toEmailList;
String emailSubject;
String emailBody;
String path;
Properties emailProperties;
Session mailSession;
MimeMessage emailMessage;
public GMail() {
}
@SuppressWarnings("rawtypes")
public GMail(String fromEmail, String fromPassword,
String toEmailList, String emailSubject, String emailBody,String path) {
this.fromEmail = fromEmail;
this.fromPassword = fromPassword;
this.toEmailList = toEmailList;
this.emailSubject = emailSubject;
this.emailBody = emailBody;
this.path = path;
emailProperties = System.getProperties();
emailProperties.put("mail.smtp.port", emailPort);
emailProperties.put("mail.smtp.auth", smtpAuth);
emailProperties.put("mail.smtp.starttls.enable", starttls);
Log.i("GMail", "Mail server properties set.");
}
public MimeMessage createEmailMessage() throws AddressException,
MessagingException, UnsupportedEncodingException {
mailSession = Session.getDefaultInstance(emailProperties, null);
emailMessage = new MimeMessage(mailSession);
emailMessage.setFrom(new InternetAddress(fromEmail, fromEmail));
Log.i("GMail", "toEmail: " + toEmailList);
emailMessage.addRecipient(Message.RecipientType.TO,
new InternetAddress(toEmailList));
emailMessage.setSubject(emailSubject);
MimeBodyPart messageBodyPart = new MimeBodyPart();
Multipart multipart = new MimeMultipart();
DataSource source = new FileDataSource(path);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName("attachmentName");
multipart.addBodyPart(messageBodyPart);
MimeBodyPart textBodyPart = new MimeBodyPart();
textBodyPart.setText(emailBody);
multipart.addBodyPart(textBodyPart);
emailMessage.setContent(multipart);
Log.i("GMail", "Email Message created.");
return emailMessage;
}
public void sendEmail() throws AddressException, MessagingException {
Transport transport = mailSession.getTransport("smtp");
transport.connect(emailHost, fromEmail, fromPassword);
Log.i("GMail", "allrecipients: " + emailMessage.getAllRecipients());
transport.sendMessage(emailMessage, emailMessage.getAllRecipients());
transport.close();
Log.i("GMail", "Email sent successfully.");
}
}
答案 0 :(得分:1)
好的我会提供一些样本来跟进
在一个活动中,您启动了一个摄像头,意图捕获像这样的图像
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
在同一个活动的onActivityResult
内,您将设置缩略图并将其写入外部存储空间
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST) {
thumbnail = (Bitmap) data.getExtras().get("data");
ImageView image = (ImageView) findViewById(R.id.imageView);
image.setImageBitmap(thumbnail);
try {
File root = Environment.getExternalStorageDirectory();
if (root.canWrite()){
pic = new File(root, "pic.png");
FileOutputStream out = new FileOutputStream(pic);
thumbnail.compress(CompressFormat.PNG, 100, out);
out.flush();
out.close();
}
} catch (IOException e) {
Log.e("BROKEN", "Could not write file " + e.getMessage());
}
}
要在电子邮件中附加图像,您将编写类似这样的内容
Intent i = new Intent(Intent.ACTION_SEND);
i.putExtra(Intent.EXTRA_EMAIL, new String[]{"email@email.com"});
i.putExtra(Intent.EXTRA_SUBJECT,"Its my attatchment");
i.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(pic)); //pic is the image you just captured
i.setType("image/png"); //format of image
startActivity(Intent.createChooser(i,"Share image"));
希望这可以帮助您完成任务。
答案 1 :(得分:1)
尝试使用此代码
public class MailImageFile extends javax.mail.Authenticator {
public MailImageFile(){}
public void Mail(String user, String pass) {
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");
Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("abc@gmail.com", "pqr123%");
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("abc@gmail.com"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("xyz@gmail.com"));
message.setContent(_multipart);
message.setSubject("Testing Subject");
message.setContent("Hi...", "text/html; charset=utf-8");
Transport.send(message);
} catch (MessagingException e) {
throw new RuntimeException(e);
}
附件代码
private Multipart _multipart; _multipart = new MimeMultipart();
public void addAttachment(String filename,String subject) throws Exception {
BodyPart messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
_multipart.addBodyPart(messageBodyPart);
BodyPart messageBodyPart2 = new MimeBodyPart();
messageBodyPart2.setText(subject);
_multipart.addBodyPart(messageBodyPart2); }}
答案 2 :(得分:1)
尝试使用image data-url。它类似于普通文本,您可以将其放在<img>
标记中,例如:
<img src="data-url">
您的头像的data-url是:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAB+ElEQVRYhaVXsWpCMRTNH9kP8FOcHDs5+g12qUs3JymCBRd/oKCDYEG6ubzCqxR9Kohv0OpyOpQb8vKSd6IJBHK8Ife83HMPRnVqKarmqLXV635jXcJvjxl+Pn9hj2x5Kezt1FK8Px/Qra8KvylGIFte9DqZnEpY1kLElViSA7idAACMWlv0G2v9dSY2byOZnJDOzxg0N87kdxPIlhd8TU+F6xUsie0hRMzkTgKz3rFyAwDskyu+P856j4mZBrr1VWHaH6g6tRQmCReBcXuHQXOj95g4VAO+qUsgJGwC++SKp4f/dTo/l3CIBoIICAmbwLi90+tBc1PCTAOUAOvzxTD31njWO9I404hifS7YVeOQONOIAqr7XLB9daFxphEl1+Hrc8F2ArPuVXGmEQVU97lgUb7MdB4WpxoAqvtcsP2FoXGqAdbngl01DIlTDbA+/3jNvTWcvhxonGqA1SjWB5jPKFajWB9gPqNYjYA4H5C4DytWI7nOe31A4j6foRoA4nxA4j6foRoA4nxA4j5MNRDrA8xnqAZifYD5DP1TyjTC+tw+b9Y7FjAlEOoTvj63zwFQIBFMgPkEezeY+00SlECoT/j63EdASJQImGMxzKkGgOo+t8+33wleAothHqQBIOzd4JtOAnbyEJ/w9fnNBOzkTAOszxmBP+5+snk2twNWAAAAAElFTkSuQmCC