天天看点

android JavaMail发送邮件(可发送附件)

http://download.csdn.net/detail/viviwen123/3677063是之前上传的资源,但只能发送普通邮件,不能发送附件。现在CSDN不知怎么了,竟然不可以修改说明,只好在此发文更正了。只要在GMailSender.java文件里加入以下函数:

public void send_mail_file(String str_title, String str_body,
			String str_from_mail, String str_to_mail, String str_file_path) {
		MimeMessage message = new MimeMessage(session); // Define message
		DataHandler handler = new DataHandler(new ByteArrayDataSource(
				str_body.getBytes(), "text/plain"));
		try {
			message.setFrom(new InternetAddress(str_from_mail)); // Set the from address
			message.addRecipient(Message.RecipientType.TO, new InternetAddress(
					str_to_mail));// Set the to address
			message.setSubject(str_title);// Set the subject
			//message.setText(str_body);// Set the content
			message.setDataHandler(handler);
		} catch (Exception e) {
		}

		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();
			Transport.send(message);// 开始发送
		} catch (MessagingException e) {
			e.printStackTrace();
		}

	}
           

调用此函数即可实现发送附件。亲测可用。