Android关于email的详细配置

作为工具类,这篇文章主要是记录一下如何配置邮件发送的username、password、

Authenticate、post、sendfrom、sendto等等详细的配置留作后用



public class EmailHelper {
	static SimpleDateFormat mDateFormat = new SimpleDateFormat(
			"yyyy-MM-dd HH:mm:ss");

	private static String mailName;// 发送者邮件账户名
	/**
	 * 发送者邮件账户密码
	 * */
	private static String mailPassword;
	/**
	 * 接收者邮件账户名
	 * */
	private static String SEND_TO_MAILLIST[];

	private static String mailHost;
	private static String mailProt;
	private static String mailSProt;

	/**
	 * @param user
	 * @param pw
	 * @param sendTo
	 */
	public static void setMailSetup(String user, String pw, String... sendTo) {
		mailName = user;
		mailPassword = pw;
		SEND_TO_MAILLIST = sendTo;
	}

	/**
	 * @param _mailHost
	 * @param port
	 * @param sport
	 */
	public static void setMailSettings(String _mailHost, String port,
			String sport) {
		mailHost = _mailHost;
		mailProt = port;
		mailSProt = sport;
	}

	/**
	 * @param title
	 * @param body
	 */
	public synchronized static void sendMail(String title, String body) {
		Mail mail = new Mail(mailName, mailPassword, SEND_TO_MAILLIST);

		StringBuffer $title = new StringBuffer();
		if (title == null) {
			title = "";
		}
		$title.append(title).append("_").append("[ ");
		$title.append(mDateFormat.format(new Date(System.currentTimeMillis())));

		mail.setTitle($title.toString());
		mail.setBody(body);
		try {
			mail.send();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * @param title
	 * @param t
	 */
	public synchronized static void sendMail(String title, Throwable t) {
		Mail mail = new Mail(mailName, mailPassword, SEND_TO_MAILLIST);

		StringBuffer $title = new StringBuffer();
		if (title == null) {
			title = "";
		}
		$title.append(title).append("_").append("[ ");
		$title.append(mDateFormat.format(new Date(System.currentTimeMillis())));

		mail.setTitle($title.toString());
		StringBuffer body = new StringBuffer();
		body.append(exceptionToString(t));
		mail.setBody(body.toString());
		try {
			mail.send();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * @param context
	 * @param logUser
	 * @param title
	 * @param t
	 */
	public synchronized static void sendMail(Context context, String logUser,
			String title, Throwable t) {
		Mail mail = new Mail(mailName, mailPassword, SEND_TO_MAILLIST);

		StringBuffer $title = new StringBuffer();
		if (title == null) {
			title = "";
		}
		$title.append(title).append("_").append("[ ");
		$title.append(mDateFormat.format(new Date(System.currentTimeMillis())));
		$title.append(" ]_");

		mail.setTitle($title.toString());

		StringBuffer body = new StringBuffer();
		body.append("LOG_USER_NAME: ").append(logUser).append("\n");
		body.append(exceptionToString(t));
		mail.setBody(body.toString());
		try {
			mail.send();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * @param context
	 * @param logUser
	 * @param title
	 * @param logs
	 * @param t
	 */
	public synchronized static void sendMail(Context context, String logUser,
			String title, String logs, Throwable t) {
		Mail mail = new Mail(mailName, mailPassword, SEND_TO_MAILLIST);

		StringBuffer $title = new StringBuffer();
		if (title == null) {
			title = "";
		}
		$title.append(title).append("_").append("[ ");
		$title.append(mDateFormat.format(new Date(System.currentTimeMillis())));
		$title.append(" ]_");
		$title.append(logUser);

		mail.setTitle($title.toString());

		StringBuffer body = new StringBuffer();
		body.append("LOG_USER_NAME: ").append(logUser).append("\n");
		body.append(logs).append('\n');
		body.append(exceptionToString(t));
		mail.setBody(body.toString());
		try {
			mail.send();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * @param context
	 * @param logUser
	 * @param filename
	 */
	public synchronized static void sendMail(Context context, String logUser,
			String filename) {
		Mail mail = new Mail(mailName, mailPassword, SEND_TO_MAILLIST);

		StringBuffer $title = new StringBuffer();
		$title.append(logUser).append("_").append("[ ");
		$title.append(mDateFormat.format(new Date(System.currentTimeMillis())));
		$title.append(" ]_");
		$title.append(logUser);

		mail.setTitle($title.toString());

		StringBuffer body = new StringBuffer();
		body.append("LOG_USER_NAME: ").append(logUser).append("\n");
		mail.setBody(body.toString());
		try {
			mail.addAttachment(filename);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		try {
			mail.send();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 将Excepiton信息转换成String字符串.
	 * 
	 * @param t
	 * @return
	 */
	public static String exceptionToString(Throwable throwable) {
		if (throwable == null) {
			return null;
		}

		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		try {
			throwable.printStackTrace(new PrintStream(baos));
		} finally {
			try {
				baos.close();
			} catch (Exception ex) {
				ex.printStackTrace();
				System.gc();
			}
		}
		return baos.toString();
	}

	private static class Mail extends javax.mail.Authenticator {
		private String _user;// 名
		private String _pass;// 密

		private String[] _to;// 送达
		private String _from;// 我

		private final String _port;
		private final String _sport;

		private final String _host;

		private String _subject;
		private String _body;

		private final boolean _auth;

		private final boolean _debuggable;

		private final Multipart _multipart;

		public Mail() {

			_host = mailHost; // default smtp server
			_port = mailProt; // default smtp port
			_sport = mailSProt; // default socketfactory port

			_user = ""; // username
			_pass = ""; // password
			_from = ""; // email sent from
			_subject = ""; // email subject
			_body = ""; // email body

			_debuggable = false; // debug mode on or off - default off
			_auth = true; // smtp authentication - default on

			_multipart = new MimeMultipart();

			if (mailName == null || mailPassword == null
					|| SEND_TO_MAILLIST == null || mailHost == null
					|| mailProt == null) {
				throw new NullPointerException("EmailHelper 配置未初始化完成");
			}

			// There is something wrong with MailCap, javamail can not find a
			// handler for the multipart/mixed part, so this bit needs to be
			// added.
			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);
		}

		public Mail(String user, String pass, String to[]) {
			this();
			_subject = "buglists";
			_user = user;
			_from = _user;
			_pass = pass;
			_to = to;
		}

		public void setTitle(String title) {
			_subject = title;
		}

		public boolean send() throws Exception {
			Properties props = _setProperties();

			if (!_user.equals("") && !_pass.equals("") && _to.length > 0
					&& !_from.equals("") && !_subject.equals("")
					&& !_body.equals("")) {
				Session session = Session.getInstance(props, this);

				MimeMessage msg = new MimeMessage(session);

				msg.setFrom(new InternetAddress(_from));

				InternetAddress[] addressTo = new InternetAddress[_to.length];
				for (int i = 0; i < _to.length; i++) {
					addressTo[i] = new InternetAddress(_to[i]);
				}
				msg.setRecipients(MimeMessage.RecipientType.TO, addressTo);

				msg.setSubject(_subject);
				msg.setSentDate(new Date());

				// setup message body
				BodyPart messageBodyPart = new MimeBodyPart();
				messageBodyPart.setText(_body);
				_multipart.addBodyPart(messageBodyPart);

				// Put parts in message
				msg.setContent(_multipart);

				// send email
				Transport.send(msg);

				return true;
			} else {
				return false;
			}
		}

		public void addAttachment(String filename) throws Exception {
			BodyPart messageBodyPart = new MimeBodyPart();
			DataSource source = new FileDataSource(filename);
			messageBodyPart.setDataHandler(new DataHandler(source));
			messageBodyPart.setFileName(filename);

			_multipart.addBodyPart(messageBodyPart);
		}

		@Override
		public PasswordAuthentication getPasswordAuthentication() {
			return new PasswordAuthentication(_user, _pass);
		}

		private Properties _setProperties() {
			Properties props = new Properties();

			props.put("mail.smtp.host", _host);

			if (_debuggable) {
				props.put("mail.debug", "true");
			}

			if (_auth) {
				props.put("mail.smtp.auth", "true");
			}

			props.put("mail.smtp.port", _port);
			props.put("mail.smtp.socketFactory.port", _sport);
			props.put("mail.smtp.socketFactory.class",
					"javax.net.ssl.SSLSocketFactory");
			props.put("mail.smtp.socketFactory.fallback", "false");

			return props;
		}

		public String getBody() {
			return _body;
		}

		public void setBody(String _body) {
			this._body = _body;
		}
	}
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
1. 安装Git 在Windows上,您可以从Git官方网站https://git-scm.com/downloads 下载并安装Git。 在Mac上,您可以使用Homebrew进行安装,打开终端并输入以下命令: ``` brew install git ``` 2. 配置Git 在Android Studio中配置Git的第一步是告诉它在哪里可以找到Git可执行文件。这需要在Android Studio的设置中完成。 打开Android Studio并转到File -> Settings。 在设置面板中,展开Version Control选项,然后选择Git。 在Git设置面板中,找到Path to Git executable选项并输入Git可执行文件的路径。如果您使用默认的安装路径,则可执行文件位于以下位置: - Windows: C:\Program Files\Git\bin\git.exe - Mac: /usr/local/git/bin/git 3. 配置Git用户名和电子邮件地址 在终端中输入以下命令以设置Git用户名和电子邮件地址: ``` git config --global user.name "Your Name" git config --global user.email "your.email@example.com" ``` 确保将您的名字和电子邮件地址替换为自己的信息。 4. 在Android Studio中使用Git 要在Android Studio中使用Git,请转到VCS -> Import into Version Control -> Share Project on GitHub。 在GitHub登录页面上,输入您的GitHub用户名和密码以授权Android Studio访问您的GitHub帐户。 在接下来的对话框中,输入项目的名称和描述,然后单击“共享”按钮。 这将在GitHub上创建一个新的代码库,并向Android Studio添加Git支持。现在,您可以使用Android Studio中的Git工具来管理和提交更改,以及与其他开发人员协作。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值