Android发带附件和图片的邮件

记得网络权限,开子线程操作。

依赖的三个jar包:activation.jar    additionnal.jar    mail.jar

下载地址:Android_Email


核心代码:

				Authenticator authenticator = new Authenticator() {
					@Override
					protected PasswordAuthentication getPasswordAuthentication() {
						return new PasswordAuthentication("[email protected]", "wyl123");
					}
				};
				//属性
				Properties props = new Properties();
				props.setProperty("mail.smtp.host", "smtp.163.com");   
		        props.put("mail.smtp.auth", "true"); 
				Session session = Session.getDefaultInstance(props, authenticator);
				
				//构建Mime消息
				MimeMessage message = new MimeMessage(session);
				//设置消息内容
				try {
					message.setFrom(new InternetAddress("[email protected]"));//发送人邮箱
					message.setSubject("邮件主题");
					message.setRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]"));//接收人邮箱
					//cc表示抄送   bcc 表示暗送
//					message.setRecipient(Message.RecipientType.CC, new InternetAddress("抄送人邮箱"));
//					message.setRecipient(Message.RecipientType.BCC, new InternetAddress("暗送人邮箱"));
					
					//正文
						//1、文本
						MimeBodyPart body_text = new MimeBodyPart();
						body_text.setContent("世界上最复杂的邮件<br><img src='cid:a'>","text/html;charset=utf-8");
						//2、图片
						MimeBodyPart body_pic = new MimeBodyPart();
						DataHandler picDataHandler = new DataHandler(new FileDataSource(new File(Environment.getExternalStorageDirectory(),"wyl.png")));
						body_pic.setDataHandler(picDataHandler);
						body_pic.setContentID("a");//和html链接的cid一致
						//3、文本和图片关系
						MimeMultipart relatedMultipart = new MimeMultipart();
						relatedMultipart.addBodyPart(body_text);
						relatedMultipart.addBodyPart(body_pic);
						relatedMultipart.setSubType("related");
						
						//将文本和图片关系封装为body一部分
						MimeBodyPart contentPart = new MimeBodyPart();
						contentPart.setContent(relatedMultipart);
						
						//4、附件
						MimeBodyPart attachment = new MimeBodyPart();
						DataHandler attachDataHandler = new DataHandler(new FileDataSource(new File(Environment.getExternalStorageDirectory(),"360断点.txt")));
						attachment.setDataHandler(attachDataHandler);
						attachment.setFileName(MimeUtility.encodeText(attachDataHandler.getName()));
					
						//5、整合上述部分
						MimeMultipart mixedMultipart = new MimeMultipart();
						mixedMultipart.addBodyPart(contentPart);//正文内容
						mixedMultipart.addBodyPart(attachment);//附件
						mixedMultipart.setSubType("mixed");
						
					message.setContent(mixedMultipart);
					//发送
					Transport.send(message);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}


你可能感兴趣的:(Android发带附件和图片的邮件)