Java 发送邮件

依赖包是:
javamail-1.4.3


// Sender, Recipient, CCRecipient, and BccRecipient are comma-separated
	// lists of addresses. Body can span multiple CR/LF-separated lines.
	// Attachments is a ///-separated list of file names.
	// template path "/usr/tmp/attachments";

	// 给用户发送多附件
	public static String Send(String _userName, String _password, String SMTPServer, String Sender, String Recipient, String CcRecipient,
			String BccRecipient, String Subject, String Body, String attachmentLists) {
		// Error status;
		String ErrorStatus = null;
		Properties props = System.getProperties();
		props.put("mail.smtp.host", SMTPServer);
		props.put("mail.smtp.auth", "true");
		final String userName = _userName;
		final String password = _password;
		// Session session = Session.getDefaultInstance(props, null);
		Session session = null;
		if (password == null) {
			session = Session.getDefaultInstance(props, null);
		} else {
			session = Session.getDefaultInstance(props, new Authenticator() {
				protected PasswordAuthentication getPasswordAuthentication() {
					return new PasswordAuthentication(userName, password);
				}
			});
		}

		try {
			// Create a message.
			MimeMessage msg = new MimeMessage(session);
			// extracts the senders and adds them to the message.
			// Sender is a comma-separated list of e-mail addresses as per
			// RFC822.
			{
				InternetAddress[] TheAddresses = InternetAddress.parse(Sender);
				msg.addFrom(TheAddresses);

			}
			// Extract the recipients and assign them to the message.
			// Recipient is a comma-separated list of e-mail addresses as per
			// RFC822.
			{
				InternetAddress[] TheAddresses = InternetAddress.parse(Recipient);
				msg.addRecipients(Message.RecipientType.TO, TheAddresses);
			}
			// Extract the Cc-recipients and assign them to the message;
			// CcRecipient is a comma-separated list of e-mail addresses as per
			// RFC822
			if (null != CcRecipient) {
				InternetAddress[] TheAddresses = InternetAddress.parse(CcRecipient);
				msg.addRecipients(Message.RecipientType.CC, TheAddresses);
			}
			// Extract the Bcc-recipients and assign them to the message;
			// BccRecipient is a comma-separated list of e-mail addresses as per
			// RFC822
			if (null != BccRecipient) {
				InternetAddress[] TheAddresses = InternetAddress.parse(BccRecipient);
				msg.addRecipients(Message.RecipientType.BCC, TheAddresses);
			}
			// Subject field
			msg.setSubject(Subject);
			// Create the Multipart to be added the parts to
			Multipart mp = new MimeMultipart();
			// Create and fill the first message part
			{
				MimeBodyPart mbp = new MimeBodyPart();
				// mbp.setText(Body);
				mbp.setContent(Body, "text/html; charset=utf-8");
				// Attach the part to the multipart;
				mp.addBodyPart(mbp);
			}

			if (null != attachmentLists && !"".equals(attachmentLists)) {
				// 如何发送单个附件路径为空 则选择发送多个附件
				int StartIndex = 0, PosIndex = 0;
				while (-1 != (PosIndex = attachmentLists.indexOf(",", StartIndex))) {
					// Create and fill other message parts;
					MimeBodyPart mbp = new MimeBodyPart();
					FileDataSource fds = new FileDataSource(attachmentLists.substring(StartIndex, PosIndex));
					mbp.setDataHandler(new DataHandler(fds));

					sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
					String fileName = "=?UTF8?B?" + enc.encode(fds.getName().getBytes()) + "?=";

					mbp.setFileName(fileName);
					mp.addBodyPart(mbp);
					PosIndex += 1;
					StartIndex = PosIndex;
				}
				// Last, or only, attachment file;
				if (StartIndex < attachmentLists.length()) {
					MimeBodyPart mbp = new MimeBodyPart();
					FileDataSource fds = new FileDataSource(attachmentLists.substring(StartIndex));
					mbp.setDataHandler(new DataHandler(fds));

					sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
					String fileName = "=?UTF8?B?" + enc.encode(fds.getName().getBytes()) + "?=";

					mbp.setFileName(fileName);
					mp.addBodyPart(mbp);
				}

			}

			// Add the Multipart to the message
			msg.setContent(mp);
			// Set the Date: header
			msg.setSentDate(new Date());
			// Send the message;
			try {
				Transport.send(msg);

			} catch (Throwable cause) {
				Throwable ex = new Throwable();
				StackTraceElement[] stackElements = ex.getStackTrace();
				StringBuffer sb = new StringBuffer();
				if (stackElements != null) {
					for (int i = 0; i < stackElements.length; i++) {
						sb.append(stackElements[i].getClassName() + "\n");
						sb.append(stackElements[i].getFileName() + "\n");
						sb.append(stackElements[i].getLineNumber() + "\n");
						sb.append(stackElements[i].getMethodName() + "\n");
						sb.append("-----------------------------------" + "\n");
					}
				}
				System.out.println(sb.toString());
				ErrorStatus += sb.toString() + cause.fillInStackTrace();
			}

		} catch (MessagingException MsgException) {
			// ErrorMessage = MsgException.toString();
			Exception TheException = null;
			if ((TheException = MsgException.getNextException()) != null)
				// ErrorMessage = ErrorMessage + "\n" + TheException.toString();
				ErrorStatus = "Exception:" + TheException.toString();
		}
		return ErrorStatus;
	} // End Send Class


sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
					String fileName = "=?UTF8?B?" + enc.encode(fds.getName().getBytes()) + "?=";


此处注意需要给文件名字编码 否则容易出现乱码

猜你喜欢

转载自zixiaolan.iteye.com/blog/2354917