java mail 实现方式别传(commons-email)

来源:互联网 发布:angularjs 解析json 编辑:程序博客网 时间:2024/04/27 18:02

所需jar包   commons-email.jar

                    commons-logging.jar

                    mail.jar(若jdk版本过低 需activation.jar)

官网:http://commons.apache.org/email/userguide.html


如果是gmail邮箱

换上这三句话

    demo.setHostName("smtp.gmail.com");
    demo.setSmtpPort(465);
    demo.setSSL(true);

A simple text email

Our first example will create a basic email message to "John Doe" and send it through your local mail server.

import org.apache.commons.mail.SimpleEmail;...  SimpleEmail email = new SimpleEmail();  email.setHostName("mail.myserver.com");  email.addTo("jdoe@somewhere.org", "John Doe");  email.setFrom("me@apache.org", "Me");  email.setSubject("Test message");  email.setMsg("This is a simple test of commons-email");  email.send();

The call to setHostName("mail.myserver.com") sets the address of the outgoing SMTP server that will be used to send the message. If this is not set, the system property "mail.host" will be used.

Sending emails with attachments

To add attachments to an email, you will need to use the MultiPartEmail class. This class works just like SimpleEmail except that it adds several overloaded attach() methods to add attachments to the email. You can add an unlimited number of attachments either inline or attached. The attachments will be MIME encoded.

The simpliest way to add the attachments is by using the EmailAttachment class to reference your attachments.

In the following example, we will create an attachment for a picture. We will then attach the picture to the email and send it.

import org.apache.commons.mail.*;...  // Create the attachment  EmailAttachment attachment = new EmailAttachment();  attachment.setPath("mypictures/john.jpg");  attachment.setDisposition(EmailAttachment.ATTACHMENT);  attachment.setDescription("Picture of John");  attachment.setName("John");  // Create the email message  MultiPartEmail email = new MultiPartEmail();  email.setHostName("mail.myserver.com");  email.addTo("jdoe@somewhere.org", "John Doe");  email.setFrom("me@apache.org", "Me");  email.setSubject("The picture");  email.setMsg("Here is the picture you wanted");  // add the attachment  email.attach(attachment);  // send the email  email.send();

You can also use EmailAttachment to reference any valid URL for files that you do not have locally. When the message is sent, the file will be downloaded and attached to the message automatically.

The next example shows how we could have sent the apache logo to John instead.

import org.apache.commons.mail.*;...  // Create the attachment  EmailAttachment attachment = new EmailAttachment();  attachment.setURL(new URL("http://www.apache.org/images/asf_logo_wide.gif"));  attachment.setDisposition(EmailAttachment.ATTACHMENT);  attachment.setDescription("Apache logo");  attachment.setName("Apache logo");  // Create the email message  MultiPartEmail email = new MultiPartEmail();  email.setHostName("mail.myserver.com");  email.addTo("jdoe@somewhere.org", "John Doe");  email.setFrom("me@apache.org", "Me");  email.setSubject("The logo");  email.setMsg("Here is Apache's logo");    // add the attachment  email.attach(attachment);  // send the email  email.send();

Sending HTML formatted email

Sending HTML formatted email is accomplished by using the HtmlEmail class. This class works exactly like the MultiPartEmail class with additional methods to set the html content, alternative text content if the reciepient does not support HTML email, and add inline images.

In this example, we will send an email message with formatted HTML content with an inline image.

import org.apache.commons.mail.HtmlEmail;...  // Create the email message  HtmlEmail email = new HtmlEmail();  email.setHostName("mail.myserver.com");  email.addTo("jdoe@somewhere.org", "John Doe");  email.setFrom("me@apache.org", "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();

First, notice that the call to embed() returns a String. This String is a randomly generated identifier that must be used to reference the image in the image tag.

Next, there was no call to setMsg() in this example. The method is still available in HtmlEmail but it should not be used if you will be using inline images. Instead, the setHtmlMsg() and setTextMsg() methods were used.

Debugging

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 toSystem.out.

Authentication

If you need to authenticate to your SMTP server, you can call thesetAuthentication(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 thejavax.mail.Authenticator object. You will need to override thegetPasswordAuthentication() method where you will handle collecting the user's information. To make use of your newAuthenticator class, use theEmail.setAuthenticator method.

Handling Bounced Messages

Normally, messages which cannot be delivered to a recipient are returned to the sender (specified with thefrom property). However, in some cases, you'll want these to be sent to a different address. To do this, simply call thesetBounceAddress(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 JavaMailSession. (Commons Email initializes the JavaMailSession usingSystem.getProperties()) If this property has not been set, then JavaMail uses the "from" address. If your email bean has thebounceAddress property set, then Commons Email uses it to set the value ofmail.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.




原创粉丝点击