Java implementation e-mail functionality

Source: Internet
Author: User

The code is as follows:

Package com.weimob.finance.utils;
Import java.io.UnsupportedEncodingException;
Import Java.util.Date;
Import java.util.List;
Import java.util.Properties;

Import Javax.activation.DataHandler;
Import Javax.activation.FileDataSource;
Import Javax.mail.Message;
Import javax.mail.MessagingException;
Import Javax.mail.Multipart;
Import javax.mail.Session;
Import Javax.mail.Transport;
Import javax.mail.internet.AddressException;
Import javax.mail.internet.InternetAddress;
Import Javax.mail.internet.MimeBodyPart;
Import Javax.mail.internet.MimeMessage;
Import Javax.mail.internet.MimeMultipart;
Import javax.mail.internet.MimeUtility;

/**
* Java Mail Tool class
*
* @author Xueqi
* @version 1.0
*
*/
public class Mailutils {
private static String host;
private static String username;
private static String password;
private static String from;
private static String Nick;

static {
try {
Test Data
Host = "smtp.qq.com";
Username = "[email protected]";
Password = "*******";
from = "[email protected]";
Nick = "Nickinfo";
Nick + from the sender information that makes up the mailbox
} catch (Exception e) {
E.printstacktrace ();
}
}

/**
* Send mail
*
* @param to
* Recipient list, to "," split
* @param subject
* Title
* @param body
* Content
* @param filepath
* Attachment list, no attachments passed null
* @return
* @throws messagingexception
* @throws addressexception
* @throws unsupportedencodingexception
*/
public static Boolean SendMail (string to, string subject, String body,
List<string> filepath) throws Addressexception, Messagingexception,
unsupportedencodingexception {
Parameter decoration
if (BODY = = null) {
BODY = "";
}
if (subject = = null) {
Subject = "no subject";
}
Create a Properties Object
Properties props = System.getproperties ();
Create a mail server
Props.put ("Mail.smtp.host", host);
Props.put ("Mail.smtp.auth", "true"); by verifying
Props.put ("Mail.smtp.port", "465");
Props.put ("Mail.transport.protocol", "SMTP");
Props.put ("Mail.smtp.ssl.enable", "true");
Props.put ("Mail.debug", "true");
Get the default Dialog object
Session session = Session.getdefaultinstance (props, null);
Creates a message and initializes the elements of the message
MimeMessage msg = new MimeMessage (session);
Nick = Mimeutility.encodetext (Nick);
Msg.setfrom (New internetaddress (Nick + "<" + from + ">"));
Create a recipient list
if (to = null && To.trim (). Length () > 0) {
string[] arr = To.split (",");
int receivercount = Arr.length;
if (Receivercount > 0) {
internetaddress[] address = new Internetaddress[receivercount];
for (int i = 0; i < Receivercount; i++) {
Address[i] = new internetaddress (Arr[i]);
}
Msg.addrecipients (Message.RecipientType.TO, address);
Msg.setsubject (subject);
The following bodypart will be added to the multipart created here
Multipart MP = new Mimemultipart ();
Attachment operation
if (filepath! = null && filepath.size () > 0) {
for (String Filename:filepath) {
MimeBodyPart MBP = new MimeBodyPart ();
Get the data source
Filedatasource FDS = new Filedatasource (filename);
Get the attachment itself and into the bodypart
Mbp.setdatahandler (New DataHandler (FDS));
Get the same file name into BodyPart
Mbp.setfilename (Fds.getname ());
Mp.addbodypart (MBP);
}
MimeBodyPart MBP = new MimeBodyPart ();
Mbp.settext (body);
Mp.addbodypart (MBP);
Remove all elements from the collection
Filepath.clear ();
Multipart added to the letter
Msg.setcontent (MP);
} else {
Set the message body
Msg.settext (body);
}
Set the sending date of the letter header
Msg.setsentdate (New Date ());
Msg.savechanges ();
Send a letter
Transport Transport = Session.gettransport ("SMTP");
Transport.connect (username, password);
Transport.sendmessage (MSG,
Msg.getrecipients (Message.RecipientType.TO));
Transport.close ();
return true;
} else {
System.out.println ("None receiver!");
return false;
}
} else {
System.out.println ("None receiver!");
return false;
}
}

public static void Main (string[] args) throws Addressexception,
Unsupportedencodingexception, Messagingexception {
SendMail ("[Email protected],[email protected]", "Registration Information Mail", "registered mail, with attachments", NULL);
System.out.println ("SendMail success!");
}
}

Preparation process:

1.QQ Mailbox Two

2. The jar package that sent the message

Mail.jar

<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.5.0-b01</version>

</dependency>

3 QQ to QQ to send mail, the sender to open a third-party login, that is, authorized login, the following is to obtain the Authorization Code explanation link

Need to start POP3 and SMTP, and click Generate Authorization Code

4.java code (attached above)

5 Run, the final display of the Mail OK is sent successfully

Problems that may be encountered in the middle:

1. E-mail, account number, incorrect password configuration leads to connection failed error!

2. The mailbox does not have the SMPT protocol turned on. As above Step 3 operation

3. Newspaper Java.io.FileNotFoundException:

The reason is that the mail jar package from eclipse conflicts with the Maven Import mail jar package, removing the mail jar from the Java EE and resolving the conflict!

Java implementation e-mail functionality

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.