Email small instance, Email instance
Import java. util. Properties;
Import javax. activation. DataHandler;
Import javax. activation. DataSource;
Import javax. activation. FileDataSource;
Import javax. mail. BodyPart;
Import javax. mail. Message;
Import javax. mail. Multipart;
Import javax. mail. Session;
Import javax. mail. internet. InternetAddress;
Import javax. mail. internet. MimeBodyPart;
Import javax. mail. internet. MimeMessage;
Import javax. mail. internet. MimeMultipart;
Import javax. mail. Transport;
Public class email {
Public void send (String emailHost, // smtp Server
String toEmail, // recipient's email address
String additionalPath, // attachment path
String additionalName, // attachment name
String myEmailUser, // sender email
String myEmailPwd, // Password
String emailTitle, // mail title
String context) {// content
Properties props = new Properties ();
Props. put ("mail. smtp. emailHost", emailHost );
Props. put ("mail. smtp. auth", "true ");
Props. put ("mail. smtp. port", "587"); // other dedicated qq
Session session = Session. getDefaultInstance (props );
Session. setDebug (true );
MimeMessage message = new MimeMessage (session );
Try {
Message. setFrom (new InternetAddress (myEmailUser); // load the sender address
Message. addRecipient (Message. RecipientType. TO, new InternetAddress (toEmail); // load the recipient address
Message. setSubject (emailTitle); // load the title
Multipart multipart = new MimeMultipart (); // Add each part of the email to the multipart object, including text content and attachments.
BodyPart contentPart = new MimeBodyPart ();
ContentPart. setText (context); // you can specify the text content of an email.
Multipart. addBodyPart (contentPart );
BodyPart messageBodyPart = new MimeBodyPart (); // Add an attachment
DataSource source = new FileDataSource (additionalPath );
MessageBodyPart. setDataHandler (new DataHandler (source); // Add the attachment content
Sun. misc. BASE64Encoder enc = new sun. misc. BASE64Encoder ();
MessageBodyPart. setFileName ("=? GBK? B? "+ Enc. encode (additionalName. getBytes () + "? = ");
Multipart. addBodyPart (messageBodyPart );
Message. setContent (multipart); // put the multipart object in the message
Message. saveChanges (); // Save the email
Transport transport = session. getTransport ("smtp"); // send an email
Transport. connect (emailHost, myEmailUser, myEmailPwd); // connect to the server mailbox
Transport. sendMessage (message, message. getAllRecipients (); // send the email
Transport. close ();
} Catch (Exception e ){
E. printStackTrace ();
}
}
Public static void main (String [] args ){
Email = new email ();
Email. send ("smtp.qq.com ",
"Xxxxxxxxx@qq.com ",
"E: \ text.txt ",
"The attachment name is random ",
"Xxxxxxxxx@qq.com ",
"Xxxxxxxxxrqudbgie", // qq is the key for enabling smtp, and others are passwords
"Test email ",
"My latest test email !! "
);
}
}