⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 email.java

📁 Java写的ERP系统
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
/******************************************************************************
 * The contents of this file are subject to the   Compiere License  Version 1.1
 * ("License"); You may not use this file except in compliance with the License
 * You may obtain a copy of the License at http://www.compiere.org/license.html
 * Software distributed under the License is distributed on an  "AS IS"  basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
 * the specific language governing rights and limitations under the License.
 * The Original Code is                  Compiere  ERP & CRM  Business Solution
 * The Initial Developer of the Original Code is Jorg Janke  and ComPiere, Inc.
 * Portions created by Jorg Janke are Copyright (C) 1999-2001 Jorg Janke, parts
 * created by ComPiere are Copyright (C) ComPiere, Inc.;   All Rights Reserved.
 * Contributor(s): ______________________________________.
 *****************************************************************************/
package org.compiere.util;

import java.sql.*;
import java.io.*;
import java.net.*;
import java.util.*;

import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
import org.apache.log4j.Logger;

import com.sun.mail.smtp.*;


/**
 *	EMail Object.
 *	Resources:
 *	http://java.sun.com/products/javamail/index.html
 * 	http://java.sun.com/products/javamail/FAQ.html
 *
 *  <p>
 *  When I try to send a message, I get javax.mail.SendFailedException:
 * 		550 Unable to relay for my-address
 *  <br>
 *  This is an error reply from your SMTP mail server. It indicates that
 *  your mail server is not configured to allow you to send mail through it.
 *
 *  @author Jorg Janke
 *  @version  $Id: EMail.java,v 1.20 2003/05/04 06:40:55 jjanke Exp $
 */
public final class EMail implements Serializable
{
	/**
	 *	Minimum conveniance Constructor for mail from current SMTPHost and User.
	 *
	 *  @param ctx  Context
	 * 	@param fromCurrentOrRequest if true get user or request - otherwise user only
	 *  @param to   Recipient EMail address
	 *  @param subject  Subject of message
	 *  @param message  The message
	 */
	public EMail (Properties ctx, boolean fromCurrentOrRequest,
		String to, String subject, String message)
	{
		this (getCurrentSmtpHost(ctx),
			fromCurrentOrRequest ? getEMail(ctx, false) : getCurrentUserEMail(ctx, false),
			to, subject, message);
		m_ctx = ctx;
	}	//	EMail

	/**
	 *	Minumum Constructor.
	 *  Need to set subject and message
	 *
	 *  @param smtpHost The mail server
	 *  @param from Sender's EMail address
	 *  @param to   Recipient EMail address
	 */
	public EMail (String smtpHost, String from, String to)
	{
		log.info("(" + smtpHost + ") " + from + " -> " + to);
		setSmtpHost(smtpHost);
		setFrom(from);
		addTo(to);
	}	//	EMail

	/**
	 *	Full Constructor
	 *
	 *  @param smtpHost The mail server
	 *  @param from Sender's EMail address
	 *  @param to   Recipient EMail address
	 *  @param subject  Subject of message
	 *  @param message  The message
	 */
	public EMail (String smtpHost, String from, String to, String subject, String message)
	{
		log.info("(" + smtpHost + ") " + from + " -> " + to + ", Subject=" + subject + ", Message=" + message);
		setSmtpHost(smtpHost);
		setFrom(from);
		addTo(to);
		setSubject (subject);
		setMessageText (message);
		m_valid = isValid (true);
	}	//	EMail

	/**	From Address				*/
	private InternetAddress     m_from;
	/** To Address					*/
	private ArrayList			m_to;
	/** CC Addresses				*/
	private ArrayList			m_cc;
	/** BCC Addresses				*/
	private ArrayList			m_bcc;
	/**	Reply To Address			*/
	private InternetAddress		m_replyTo;
	/**	Mail Subject				*/
	private String  			m_subject;
	/** Mail Plain Message			*/
	private String  			m_messageText;
	/** Mail HTML Message			*/
	private String  			m_messageHTML;
	/**	Mail SMTP Server			*/
	private String  			m_smtpHost;
	/**	Attachments					*/
	private ArrayList			m_attachments;
	/**	UserName and Password		*/
	private EMailAuthenticator	m_auth = null;
	/**	Message						*/
	private SMTPMessage 		m_msg = null;
	/** Comtext - may be null		*/
	private Properties			m_ctx;

	/**	Info Valid					*/
	private boolean m_valid = false;

	/**	Mail Sent OK Status				*/
	public static final String      SENT_OK = "OK";

	/**	Client SMTP CTX key				*/
	public static final String		CTX_SMTP = "#Client_SMTP";
	/**	User EMail CTX key				*/
	public static final String		CTX_EMAIL = "#User_EMail";
	public static final String		CTX_EMAIL_USER = "#User_EMailUser";
	public static final String		CTX_EMAIL_USERPW = "#User_EMailUserPw";
	/**	Request EMail CTX key			*/
	public static final String		CTX_REQUEST_EMAIL = "#Request_EMail";
	public static final String		CTX_REQUEST_EMAIL_USER = "#Request_EMailUser";
	public static final String		CTX_REQUEST_EMAIL_USERPW = "#Request_EMailUserPw";

	/**	Logger							*/
	protected Logger			log = Logger.getLogger (getClass());
	/**	Logger							*/
	protected static Logger		s_log = Logger.getLogger (EMail.class);

	/**
	 *	Send Mail direct
	 *	@return OK or error message
	 */
	public String send ()
	{
		log.info("send (" + m_smtpHost + ") " + m_from + " -> " + m_to);
		//
		if (!isValid(true))
			return "Invalid Data";
		//
		Properties props = System.getProperties();
		props.put("mail.store.protocol", "smtp");
		props.put("mail.transport.protocol", "smtp");
		props.put("mail.host", m_smtpHost);
		//
		setEMailUser();
		if (m_auth != null)
			props.put("mail.smtp.auth","true");
		Session session = Session.getDefaultInstance(props, m_auth);
		session.setDebug(Log.isTraceLevel(10));

		try
		{
		//	m_msg = new MimeMessage(session);
			m_msg = new SMTPMessage(session);
			//	Addresses
			m_msg.setFrom(m_from);
			InternetAddress[] rec = getTos();
			if (rec.length == 1)
				m_msg.setRecipient (Message.RecipientType.TO, rec[0]);
			else
				m_msg.setRecipients (Message.RecipientType.TO, rec);
			rec = getCcs();
			if (rec != null && rec.length > 0)
				m_msg.setRecipients (Message.RecipientType.CC, rec);
			rec = getBccs();
			if (rec != null && rec.length > 0)
				m_msg.setRecipients (Message.RecipientType.BCC, rec);
			if (m_replyTo != null)
				m_msg.setReplyTo(new Address[] {m_replyTo});
			//
			m_msg.setSentDate(new java.util.Date());
			m_msg.setHeader("Comments", "CompiereMail");
		//	m_msg.setDescription("Description");
			//	SMTP specifics
			m_msg.setAllow8bitMIME(true);
			//	Send notification on Failure & Success - no way to set envid in Java yet
			m_msg.setNotifyOptions (SMTPMessage.NOTIFY_FAILURE | SMTPMessage.NOTIFY_SUCCESS);
			//	Bounce only header
			m_msg.setReturnOption (SMTPMessage.RETURN_HDRS);
		//	m_msg.setHeader("X-Mailer", "msgsend");
			//
			setContent();
			m_msg.saveChanges();
			//
		//	Transport.send(msg);
			Transport t = session.getTransport("smtp");
			t.connect();
		//	t.connect(m_smtpHost, user, password);
			t.send(m_msg);
		//	t.sendMessage(msg, msg.getAllRecipients());
			log.debug("send success - MessageID=" + m_msg.getMessageID());
		}
		catch (MessagingException me)
		{
			Exception ex = me;
			StringBuffer sb = new StringBuffer("send(ME)");
			boolean printed = false;
			do
			{
				if (ex instanceof SendFailedException)
				{
					SendFailedException sfex = (SendFailedException)ex;
					Address[] invalid = sfex.getInvalidAddresses();
					if (!printed)
					{
						if (invalid != null && invalid.length > 0)
						{
							sb.append (" - Invalid:");
							for (int i = 0; i < invalid.length; i++)
								sb.append (" ").append (invalid[i]);

						}
						Address[] validUnsent = sfex.getValidUnsentAddresses ();
						if (validUnsent != null && validUnsent.length > 0)
						{
							sb.append (" - ValidUnsent:");
							for (int i = 0; i < validUnsent.length; i++)
								sb.append (" ").append (validUnsent[i]);
						}
						Address[] validSent = sfex.getValidSentAddresses ();
						if (validSent != null && validSent.length > 0)
						{
							sb.append (" - ValidSent:");
							for (int i = 0; i < validSent.length; i++)
								sb.append (" ").append (validSent[i]);
						}
						printed = true;
					}
					if (sfex.getNextException() == null)
						sb.append(" ").append(sfex.getLocalizedMessage());
				}
				else if (ex instanceof AuthenticationFailedException)
				{
					sb.append(" - Invalid Username/Password");
				}
				else
				{
					String msg = ex.getLocalizedMessage();
					if (msg == null)
						msg = ex.toString();
					sb.append(" ").append(msg);
				}
				if (ex instanceof MessagingException)
					ex = ((MessagingException)ex).getNextException();
				else
					ex = null;
			} while (ex != null);
			log.error(sb.toString(), me);
			return sb.toString();
		}
		catch (Exception e)
		{
			log.error("send", e);
			return "EMail.send: " + e.getLocalizedMessage();
		}
		//
		if (Log.isTraceLevel(9))
			dumpMessage();
		return SENT_OK;
	}	//	send

	/**
	 * 	Dump Message Info
	 */
	private void dumpMessage()
	{
		if (m_msg == null)
			return;
		try
		{
			Enumeration e = m_msg.getAllHeaderLines ();
			while (e.hasMoreElements ())
				log.debug("- " + e.nextElement ());
		}
		catch (MessagingException ex)
		{
			log.error("dumpMessage", ex);
		}
	}	//	dumpMessage

	/**
	 * 	Get the message directly
	 * 	@return mail message
	 */
	protected MimeMessage getMimeMessage()
	{
		return m_msg;
	}	//	getMessage

	/**
	 * 	Get Message ID or null
	 * 	@return Message ID e.g. <20030130004739.15377.qmail@web13506.mail.yahoo.com>
	 *  <25699763.1043887247538.JavaMail.jjanke@main>
	 */
	public String getMessageID()
	{
		try
		{
			if (m_msg != null)
				return m_msg.getMessageID ();
		}
		catch (MessagingException ex)
		{
			log.error("getMessageID", ex);
		}
		return null;
	}	//	getMessageID

	/*************************************************************************/

	/**
	 *	Get the EMail Address of current user or request
	 *  @param ctx  Context
	 * 	@param strict no bogous email address
	 *  @return EMail Address
	 */
	public static String getEMail (Properties ctx, boolean strict)
	{
		String from = Env.getContext(ctx, CTX_EMAIL);
		if (from.length() != 0)
			return from;

		int AD_User_ID = Env.getContextAsInt (ctx, "#AD_User_ID");
		if (AD_User_ID != 0)
			from = getCurrentUserEMail (ctx, true);
		if (from == null || from.length() == 0)
			from = getRequestEMail (ctx);
		//	bogus
		if (from == null || from.length() == 0)
		{
			if (strict)
				return null;
			from = getBogusEMail(ctx);
		}
		return from;
	}   //  getCurrentUserEMail

	/**
	 *  Get Email Address of AD_User
	 *  @param AD_User_ID user
	 * 	@param strict no bogous email address
	 * 	@param ctx optional context
	 *  @return EMail Address
	 */
	public static String getEMailOfUser (int AD_User_ID, boolean strict, Properties ctx)
	{
		String email = null;
		//	Get ID
		String sql = "SELECT u.EMail,bpc.EMail, u.EMailUser, u.EMailUserPw "
			+ "FROM AD_User u"
			+ " LEFT OUTER JOIN C_BPartner bp ON (u.C_BPartner_ID=bp.C_BPartner_ID)"
			+ " LEFT OUTER JOIN C_BPartner_Contact bpc ON (u.C_BPartner_ID=bpc.C_BPartner_ID) "
			+ "WHERE u.AD_User_ID=?";
		try
		{
			PreparedStatement pstmt = DB.prepareStatement(sql);
			pstmt.setInt(1, AD_User_ID);
			ResultSet rs = pstmt.executeQuery();
			while (rs.next() && email == null)
			{
				email = rs.getString(1);
				if (email == null)
					email = rs.getString(2);
				if (email != null)
				{
					email = cleanUpEMail(email);
					if (ctx != null)
					{
						Env.setContext (ctx, CTX_EMAIL, email);
						Env.setContext (ctx, CTX_EMAIL_USER, rs.getString (3));
						Env.setContext (ctx, CTX_EMAIL_USERPW, rs.getString (4));
					}
				}
			}
			rs.close();
			pstmt.close();
		}
		catch (SQLException e)
		{
			s_log.error("getEMailOfUser - " + sql, e);
		}
		if (email == null || email.length() == 0)
		{
			s_log.warn("getEMailOfUser - EMail not found - AD_User_ID=" + AD_User_ID);
			if (strict)
				return null;
			email = getBogusEMail(ctx == null ? Env.getCtx() : ctx);
		}
		return email;
	}	//	getEMailOfUser

	/**
	 *  Get Email Address of AD_User
	 *  @param AD_User_ID user
	 *  @return EMail Address
	 */
	public static String getEMailOfUser (int AD_User_ID)
	{
		return getEMailOfUser(AD_User_ID, false, null);
	}	//	getEMailOfUser

	/**
	 *  Get Email Address current AD_User
	 *  @param ctx  Context
	 * 	@param strict no bogous email address
	 *  @return EMail Address
	 */
	public static String getCurrentUserEMail (Properties ctx, boolean strict)
	{
		String from = Env.getContext(ctx, CTX_EMAIL);
		if (from.length() != 0)
			return from;

		int AD_User_ID = Env.getContextAsInt (ctx, "#AD_User_ID");
		from = getEMailOfUser(AD_User_ID, strict, ctx);
		return from;
	}	//	getCurrentUserEMail

	/**
	 * 	Clean up EMail address
	 *	@param email email address
	 *	@return lower case email w/o spaces
	 */
	private static String cleanUpEMail (String email)
	{
		if (email == null || email.length() == 0)
			return "";
		//
		email = email.trim().toLowerCase();
		//	Delete all spaces
		int pos = email.indexOf(" ");
		while (pos != -1)
		{
			email = email.substring(0, pos) + email.substring(pos+1);
			pos = email.indexOf(" ");
		}
		return email;
	}	//	cleanUpEMail

	/**
	 * 	Construct Bogos email
	 *	@param ctx Context
	 *	@return userName.ClientName.com
	 */
	public static String getBogusEMail (Properties ctx)
	{
		String email = System.getProperty("user.name") + "@"
			+ Env.getContext(ctx, "#AD_Client_Name") + ".com";
		email = cleanUpEMail(email);
		return email;
	}	//	getBogusEMail

	/**
	 *  Get Name of AD_User
	 *  @param  AD_User_ID   System User
	 *  @return Name of user
	 */
	public static String getNameOfUser (int AD_User_ID)
	{
		String name = null;
		//	Get ID
		String sql = "SELECT Name FROM AD_User WHERE AD_User_ID=?";
		try
		{
			PreparedStatement pstmt = DB.prepareStatement(sql);
			pstmt.setInt(1, AD_User_ID);
			ResultSet rs = pstmt.executeQuery();
			if (rs.next())
				name = rs.getString(1);
			rs.close();
			pstmt.close();
		}
		catch (SQLException e)
		{
			s_log.error("getNameOfUser", e);
		}
		return name;
	}	//	getNameOfUser

	/**
	 * 	Get Client Request EMail
	 *  @param ctx  Context
	 *  @return Request EMail Address
	 */
	public static String getRequestEMail (Properties ctx)
	{
		String email = Env.getContext(ctx, CTX_REQUEST_EMAIL);
		if (email.length() != 0)
			return email;

		String sql = "SELECT RequestEMail, RequestUser, RequestUserPw "
			+ "FROM AD_Client "
			+ "WHERE AD_Client_ID=?";
		PreparedStatement pstmt = null;
		try
		{
			pstmt = DB.prepareStatement(sql);
			pstmt.setInt(1, Env.getContextAsInt(ctx, "#AD_Client_ID"));
			ResultSet rs = pstmt.executeQuery();
			if (rs.next())
			{
				email = rs.getString (1);
				email = cleanUpEMail(email);
				Env.setContext(ctx, CTX_REQUEST_EMAIL, email);
				Env.setContext(ctx, CTX_REQUEST_EMAIL_USER, rs.getString(2));
				Env.setContext(ctx, CTX_REQUEST_EMAIL_USERPW, rs.getString(3));
			}
			rs.close();
			pstmt.close();
			pstmt = null;
		}
		catch (Exception e)
		{
			s_log.error("getRequestEMail", e);
		}
		finally
		{
			try
			{
				if (pstmt != null)
					pstmt.close ();
			}
			catch (Exception e)
			{}
			pstmt = null;
		}
		return email;
	}	//	getRequestEMail

	/**************************************************************************
	 *	Get the current Client EMail SMTP Host
	 *  @param ctx  Context
	 *  @return Mail Host
	 */
	public static String getCurrentSmtpHost (Properties ctx)
	{
		String SMTP = Env.getContext(ctx, CTX_SMTP);
		if (SMTP.length() != 0)
			return SMTP;
		//	Get SMTP name
		SMTP = getSmtpHost (Env.getContextAsInt(ctx, "#AD_Client_ID"));
		if (SMTP == null)
			SMTP = "localhost";
		Env.setContext(ctx, CTX_SMTP, SMTP);
		return SMTP;
	}   //  getCurrentSmtpHost

	/**
	 *  Get SMTP Host of Client
	 *  @param AD_Client_ID  Client
	 *  @return Mail Host
	 */
	public static String getSmtpHost (int AD_Client_ID)
	{
		String SMTP = null;
		String sql = "SELECT SMTPHost FROM AD_Client "
			+ "WHERE AD_Client_ID=?";
		try
		{
			PreparedStatement pstmt = DB.prepareStatement(sql);
			pstmt.setInt(1, AD_Client_ID);
			ResultSet rs = pstmt.executeQuery();
			if (rs.next())
				SMTP = rs.getString(1);
			rs.close();
			pstmt.close();
		}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -