Java Email

 1.简单电子邮件例子之二: 
  
Email email = new SimpleEmail();
        email.setHostName("smtp.qq.com");//qq
        email.setSmtpPort(465);//iport
        email.setAuthenticator(new DefaultAuthenticator("fromUserName", "fromUserPwd"));
        email.setSSLOnConnect(true);
        try {
            email.setFrom("fromUserName@**.com");
            email.setSubject("TestMail");
            email.setMsg("This is a test mail ... :-)");
            email.addTo("toUserName@**.com");
            email.send();
        } catch (EmailException e) {
            e.printStackTrace();
        }
//第二个
Email email = new SimpleEmail();
        email.setHostName("smtp.qq.com");
        email.setAuthentication("fromUserName", "fromUserPwd");
        email.setCharset("UTF-8"); 
        email.setTLS(true); 
        try {
            email.setFrom("fromUserName@**.com");
            email.setSubject("TestMail");
            email.setMsg("This is a test mail ... :-)");
            email.addTo("toUserName@**.com");
            email.send();
        } catch (EmailException e) {
            e.printStackTrace();
        }
2.添加附件,附件都是MIME进行编码
以下这种方式,添加的附件是失败的, 附件的类型错误,但是内容正确
EmailAttachment attachment = new EmailAttachment();
		  attachment.setPath("g:/promise.jpg");
		  attachment.setDisposition(EmailAttachment.ATTACHMENT);
		  attachment.setDescription("to me");
		  attachment.setName("to me ");

		  // Create the email message
		  MultiPartEmail email = new MultiPartEmail();
		  email.setHostName("smtp.qq.com");
//		  email.setSmtpPort(465);//iport
//		  email.setAuthenticator(new DefaultAuthenticator("fromUserName", "fromUserPwd"));
//		  email.setSSLOnConnect(true);
		  email.setAuthentication("fromUserName", "fromUserPwd");
		  email.setCharset("UTF-8"); 
			email.setTLS(true); 
		  try {
			  email.addTo("toUserName@**.com");
			  email.setFrom("fromUserName@**.com", "Me");
			  email.setSubject("The picture");
			  email.setMsg("Here is the picture you wanted");

			  // add the attachment
			  email.attach(attachment);

			  // send the email
			  email.send();
		} catch (EmailException e) {
			e.printStackTrace();
		}
第二个,发送特定url下的资源,作为附件
EmailAttachment attachment = new EmailAttachment();
		 try {
			 //特定url出资源作为附件,发送,在接收的时候,会下载该资源,然后作为附件
				attachment.setURL(new URL("http://www.apache.org/images/asf_logo_wide.gif"));
			} catch (MalformedURLException e1) {
				e1.printStackTrace();
			}
		//  attachment.setPath("g:\\promise.jpg");
		  attachment.setDisposition(EmailAttachment.ATTACHMENT);
		  attachment.setDescription("to me");
		  attachment.setName("to me ");

		  // Create the email message
		  MultiPartEmail email = new MultiPartEmail();
		  email.setHostName("smtp.qq.com");
//		  email.setSmtpPort(465);//iport
//		  email.setAuthenticator(new DefaultAuthenticator("fromUserName", "fromUserPwd"));
//		  email.setSSLOnConnect(true);
		  email.setAuthentication("fromUserName", "fromUserPwd");
		  email.setCharset("UTF-8"); 
			email.setTLS(true); 
		  try {
			  email.addTo("toUserName@**.com");
			  email.setFrom("fromUserName@**.com", "Me");
			  email.setSubject("The picture");
			  email.setMsg("Here is the picture you wanted");

			  // add the attachment
			  email.attach(attachment);

			  // send the email
			  email.send();
		} catch (EmailException e) {
			e.printStackTrace();
		}
3.发送页面邮件
	// Create the email message
		  HtmlEmail email = new HtmlEmail();
		  email.setHostName("smtp.qq.com");
		  email.setAuthentication("fromUserName", "fromUserPwd");
		  email.setCharset("UTF-8"); 
		  email.setTLS(true); 
		  
		  try {
			email.addTo("[email protected]", "John Doe");
			  email.setFrom("[email protected]", "Me");
			  email.setSubject("Test email with inline image");
			  
			  // embed the image and get the content id
			  URL url = new URL("http://www.apache.org/images/asf_logo_wide.gif");
			  String cid = email.embed(url, "Apache logo");
			  
			  // set the html message
			  email.setHtmlMsg("<html>The apache logo - <img src=\"cid:"+cid+"\"></html>");

			  // set the alternative message
			  email.setTextMsg("Your email client does not support HTML messages");

			  // send the email
			  email.send();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (EmailException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
补充内容:

The JavaMail API supports a debugging option that will can be very useful if you run into problems. You can activate debugging on any of the mail classes by calling setDebug(true). The debugging output will be written to System.out.

Sometimes you want to experiment with various security setting or features of commons-email. A good starting point is the test class EmailLiveTest and EmailConfigurationwhich are used for testing commons-email with real SMTP servers.

Authentication

If you need to authenticate to your SMTP server, you can call the setAuthentication(userName,password) method before sending your email. This will create an instance ofDefaultAuthenticator which will be used by the JavaMail API when the email is sent. Your server must support RFC2554 in order for this to work.

You can perform a more complex authentication method such as displaying a dialog box to the user by creating a subclass of the javax.mail.Authenticator object. You will need to override the getPasswordAuthentication() method where you will handle collecting the user's information. To make use of your new Authenticator class, use theEmail.setAuthenticator method.

Security

Nowadays you should not use plain SMTP protocol when using public SMTP servers but there is a some confusion regarding the available options.

Two commons options are using

  • STARTTLS on port 25
  • SSL on port 465
The following definitions were taken from Wikipedia
  • STARTTLS is an extension to plain text communication protocols, which offers a way to upgrade a plain text connection to an encrypted (TLS or SSL) connection instead of using a separate port for encrypted communication.
  • Transport Layer Security (TLS) and its predecessor, Secure Sockets Layer (SSL), are cryptographic protocols that provide communication security over the Internet.TLS and SSL encrypt the segments of network connections above the Transport Layer, using asymmetric cryptography for key exchange, symmetric encryption for privacy, and message authentication codes for message integrity.
In addition you can force the following security checks (which are disabled by default)
  • When using a secured transport (STARTTLS or SSL) you can force validating the server's certificate by calling Email.setSSLCheckServerIdentity(true). Having said that this does not seem to work on any of my test servers (GMAIL, GMX).
  • Enforce using STARTTLS by calling Email.setStartTLSRequired(true)

Handling Bounced Messages

Normally, messages which cannot be delivered to a recipient are returned to the sender (specified with the from property). However, in some cases, you'll want these to be sent to a different address. To do this, simply call the setBounceAddress(emailAddressString) method before sending your email.

Technical notes: When SMTP servers cannot deliver mail, they do not pay any attention to the contents of the message to determine where the error notification should be sent. Rather, they refer to the SMTP "envelope sender" value. JavaMail sets this value according to the value of the mail.smtp.from property on the JavaMail Session. (Commons Email initializes the JavaMail Session using System.getProperties()) If this property has not been set, then JavaMail uses the "from" address. If your email bean has the bounceAddress property set, then Commons Email uses it to set the value of mail.smtp.from when the Session is initialized, overriding any other value which might have been set.

Note: This is the only way to control the handling of bounced email. Specifically, the "Errors-to:" SMTP header is deprecated and cannot be trusted to control how a bounced message will be handled. Also note that it is considered bad practice to send email with an untrusted "from" address unless you also set the bounce address. If your application allows users to enter an address which is used as the "from" address on an email, you should be sure to set the bounce address to a known good address.






参考资料:

你可能感兴趣的:(java,email)