android--email发送邮件,文本还有附件形式的邮件
1.首先用的jar包为javaemail
下载地址:
https://yunpan.cn/cB3kY8WIvcGtU (提取码:e042)
2.工具包
package com.kllayhello.utils; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.util.Log; import java.util.Properties; import javax.activation.CommandMap; import javax.activation.DataHandler; import javax.activation.FileDataSource; import javax.activation.MailcapCommandMap; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Multipart; 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 javax.mail.internet.MimeUtility; import javax.mail.util.ByteArrayDataSource; /** * Created by Administrator on 2016/6/30. * http://www.jb51.net/article/38158.htm * http://blog.csdn.net/svenke2011/article/details/8229521 * * http://blog.csdn.net/mad1989/article/details/25964495 * * http://blog.csdn.net/chinafe/article/details/7183400 *http://blog.csdn.net/xanxus46/article/details/8296529 * http://blog.csdn.net/kudy21/article/details/7665434 */ public class EmailUtils{ /** * android内部发送邮件 * 调用手机邮箱 * 不能自动发送 * sendto 发送邮件 * */ public void sendTOEmail(String title,String content,Context context){ Intent data=new Intent(Intent.ACTION_SENDTO); data.setData(Uri.parse("mailto:qg@17xu.com")); data.putExtra(Intent.EXTRA_SUBJECT, title); data.putExtra(Intent.EXTRA_TEXT, content); context.startActivity(data); } /** * 调用手机邮箱待附件的 * 不能自动发送 * */ public void sendToFileEmail(String title,String content,Context context){ Intent intent = new Intent(Intent.ACTION_SEND); String[] tos = { "qq@17xu.com" }; String[] ccs = { "qq@17xu.com" }; String[] bccs = {"qq@17xu.com"}; intent.putExtra(Intent.EXTRA_EMAIL, tos); intent.putExtra(Intent.EXTRA_CC, ccs); intent.putExtra(Intent.EXTRA_BCC, bccs); intent.putExtra(Intent.EXTRA_TEXT, content); intent.putExtra(Intent.EXTRA_SUBJECT, title); intent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file:///mnt/sdcard/qq.png")); intent.setType("image/*"); intent.setType("message/rfc882"); Intent.createChooser(intent, "Choose Email Client"); context.startActivity(intent); } /** * 发送邮件 * */ /** * 邮件发送程序 * * @param host * 邮件服务器 如:smtp.qq.com * @param address * 发送邮件的地址 如:qq@qq.com * @param from * 来自: qq@qq.com * @param password * 您的邮箱密码 * @param to * 接收人 * @param port * 端口(QQ:25) * @param subject * 邮件主题 * @param content * 邮件内容 * @throws Exception */ public void SendEmail(String host, String address, String from, String password, String to, String port, String subject, String content) throws Exception { Multipart multiPart; String finalString = ""; Properties props = System.getProperties(); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", host); props.put("mail.smtp.user", address); props.put("mail.smtp.password", password); props.put("mail.smtp.port", port); props.put("mail.smtp.auth", "true"); Log.i("Check", "done pops"); Session session = Session.getDefaultInstance(props, null); DataHandler handler = new DataHandler(new ByteArrayDataSource(finalString.getBytes(), "text/plain")); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.setDataHandler(handler); Log.i("Check", "done sessions"); multiPart = new MimeMultipart(); InternetAddress toAddress; toAddress = new InternetAddress(to); message.addRecipient(Message.RecipientType.TO, toAddress); Log.i("Check", "added recipient"); message.setSubject(subject); message.setContent(multiPart); message.setText(content); Log.i("check", "transport"); Transport transport = session.getTransport("smtp"); Log.i("check", "connecting"); transport.connect(host, address, password); Log.i("check", "wana send"); transport.sendMessage(message, message.getAllRecipients()); transport.close(); Log.i("check", "sent"); } /** * 发送附件邮件 * http://cuisuqiang.iteye.com/blog/1586023 * */ /** * 邮件发送程序 * * @param host * 邮件服务器 如:smtp.qq.com * @param address * 发送邮件的地址 如:qq@qq.com * @param from * 来自: qq@qq.com * @param password * 您的邮箱密码 * @param to * 接收人 * @param port * 端口(QQ:25) * @param subject * 邮件主题 * @param content * 邮件内容 * @throws Exception */ public void SendEmailfile(String host, String address, String from, String password, String to, String port, String subject, String content,String file_path) throws Exception { MimeMultipart multiPart; String finalString = ""; Properties props = System.getProperties(); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", host); props.put("mail.smtp.user", address); props.put("mail.smtp.password", password); props.put("mail.smtp.port", port); props.put("mail.smtp.auth", "true"); Session session = Session.getDefaultInstance(props, null); DataHandler handler = new DataHandler(new ByteArrayDataSource(finalString.getBytes(), "text/plain")); MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.setDataHandler(handler); multiPart = new MimeMultipart("mixed"); //附件 InternetAddress toAddress; toAddress = new InternetAddress(to); message.addRecipient(Message.RecipientType.TO, toAddress); //添加收件人 Log.i("Check", "added recipient"); message.setSubject(subject); // 邮件内容 MimeBodyPart htmlPart = new MimeBodyPart(); htmlPart.setContent( "<body background='#'>" + "<div style='position: absolute; left: 390px; top: 150px;height: " + "100px;width: 200px;' align='center'>" + "<font color='red'>这是测试邮件,请勿回复</font>" + "</div></body>", "text/html;charset=UTF-8"); // TODO 组装的顺序非常重要,一定要先组装文本域,再组装文件 multiPart.addBodyPart(htmlPart); //附件添加 try{ MimeBodyPart attachPart = new MimeBodyPart(); FileDataSource fds = new FileDataSource(file_path); //打开要发送的文件 DataHandler dh=new DataHandler(fds); attachPart.setDataHandler(dh); attachPart.setFileName(MimeUtility.encodeText(dh.getName())); //设置名称 multiPart.addBodyPart(attachPart); //添加附件 message.setContent(multiPart); //附件设置内容 message.saveChanges(); //保存邮件 }catch (Exception e){ System.out.print("File Bug:::"+e.getMessage()); } Transport transport = session.getTransport("smtp"); transport.connect(host, address, password); transport.sendMessage(message, message.getAllRecipients()); transport.close(); Log.i("check", "sent"); System.out.println("send success!"); } /** * 暂时不能用,有时间再研究 * 发送待附件的邮件 *str_to_mail 发邮件的目的地(收件人信箱) * str_from_mail 发邮件的出发地(发件人的信箱) * str_smtp host 发件人使用发邮件的电子信箱服务器 * str_user 发件人用户名 * str_pass 发件人密码 * str_title 邮件标题 * str_body 邮件内容 * str_file_path 附件 * */ public void send_mail_file(String str_to_mail,String str_from_mail,String str_smtp,String str_user,String str_pass,String ports,String str_title,String str_body,String str_file_path) { Log.v("filesend","send_mail_file"); String host = str_smtp; //发件人使用发邮件的电子信箱服务器 String from = str_from_mail; //发邮件的出发地(发件人的信箱) String to = str_to_mail; //发邮件的目的地(收件人信箱) Log.v("filesend",str_smtp); Log.v("filesend",str_from_mail); Log.v("filesend",str_to_mail); Properties props = System.getProperties();// Get system properties props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", host);// Setup mail server //发件人邮箱和密码 props.put("mail.smtp.user", str_user); props.put("mail.smtp.password", str_pass); props.put("mail.smtp.port", ports); props.put("mail.smtp.auth", "true"); //这样才能通过验证 Session session = Session.getDefaultInstance(props, null); MimeMessage message = new MimeMessage(session); // Define message try { message.setFrom(new InternetAddress(from)); // Set the from address } catch (MessagingException e) { e.printStackTrace(); } try { message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));// Set the to address message.setSubject(str_title);// Set the subject message.setText(str_body);// Set the content } catch (MessagingException e) { e.printStackTrace(); } MimeBodyPart attachPart = new MimeBodyPart(); FileDataSource fds = new FileDataSource(str_file_path); //打开要发送的文件 try { attachPart.setDataHandler(new DataHandler(fds)); attachPart.setFileName(fds.getName()); } catch (MessagingException e) { e.printStackTrace(); } MimeMultipart allMultipart = new MimeMultipart("mixed"); //附件 try { allMultipart.addBodyPart(attachPart);//添加 message.setContent(allMultipart); message.saveChanges(); } catch (MessagingException e) { e.printStackTrace(); } try { //报错解决方法 MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap(); mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html"); mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml"); mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain"); mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed"); mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822"); CommandMap.setDefaultCommandMap(mc); Transport.send(message);//开始发送 } catch (MessagingException e) { e.printStackTrace(); } } }
3.使用工具包:
but_emailtest.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //使用HandlerThread mhandlerthread=new HandlerThread("myhandlerthread"); mhandlerthread.start(); mhandler = new Handler(mhandlerthread.getLooper()); mhandler.post(mRunnable); } }); } Runnable mRunnable = new Runnable() { @Override public void run() { NetworkUtils nu=new NetworkUtils(); EmailUtils email=new EmailUtils(); //emsuper.run();ail.sendToFileEmail("哈哈哈test","这是荣哦支持你下哈哈",MinShiLi.this); String to="fajianren@17xu.com"; String host = "smtp.17xu.com"; String address = "88888@17xu.com"; //发件人地址 String from = "88888@17xu.com"; String password = "******";// 密码 String filepath=nu.getSDPath()+"/"+"qq.png"; String port = "25"; //发邮件端口号 try { //email.SendEmail(host, address, from, password, to, port, "主题测试", "内容哦哈哈哈哈哈哈哈"); //附件 email.SendEmailfile(host, address, from, password, to, port, "主题测试", "内容哦哈哈哈哈哈哈哈",filepath); } catch (Exception e) { e.printStackTrace(); } } };
4.sd卡获取文件路径、判断网络是否链接
package com.kllayhello.utils; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Environment; import java.io.File; /** * Created by Administrator on 2016/6/30. */ public class NetworkUtils { /** * 判断网络是否链接 * */ public boolean isNetworkConnected(Context context) { if (context != null) { ConnectivityManager mConnectivityManager = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo(); if (mNetworkInfo != null) { return mNetworkInfo.isAvailable(); } } return false; } /** * 判断sd卡是否存在 并获取路径 * */ public String getSDPath(){ File sdDir = null; boolean sdCardExist = Environment.getExternalStorageState() .equals(android.os.Environment.MEDIA_MOUNTED);//判断sd卡是否存在 if(sdCardExist) { sdDir = Environment.getExternalStorageDirectory();//获取跟目录 } return sdDir.toString(); } }
参考文件:
* http://cuisuqiang.iteye.com/blog/1586023
* http://www.jb51.net/article/38158.htm
* http://blog.csdn.net/svenke2011/article/details/8229521
*
* http://blog.csdn.net/mad1989/article/details/25964495
*
* http://blog.csdn.net/chinafe/article/details/7183400
*http://blog.csdn.net/xanxus46/article/details/8296529
* http://blog.csdn.net/kudy21/article/details/7665434