Java implements email sending with attachments

Source: Internet
Author: User
Tags email account

I. Objectives

Use java code to send emails with attachments

Ii. Learning address

Iii. preparations:

Add jar package: javamail4104_5.zip

[Java]
Public class SendMailService {
Private MailInformation mailInfor;
Private static SendMailService sendMailService;

Public void setMailInfor (MailInformation mailInfor ){
This. mailInfor = mailInfor;
}
 
Public static SendMailService getService (){
If (sendMailService = null ){
SendMailService = new SendMailService ();
}
Return sendMailService;
}
/**
* This code is used to send an ordinary email with an attachment.
*/
Public void send () throws Exception {
Try {
Properties props = new Properties (); // obtain the system environment
Authenticator auth = new Email_Autherticator (); // Authenticator
Props. put ("mail. smtp. host", mailInfor. getHost ());
Props. put ("mail. smtp. auth", "true ");
Session session = Session. getDefaultInstance (props, auth );
// Display the execution process information on the console
Session. setDebug (true );
// Set the session to communicate with the email server.
MimeMessage message = new MimeMessage (session );
Message. setSubject (mailInfor. getMail_subject (); // you can specify the mail title.
Message. setSentDate (new Date (); // you can specify the mail sending Date.
Address address = new InternetAddress (mailInfor. getSendEmail (),
MailInfor. getSendPassword ());
Message. setFrom (address); // you can specify the sender's address.
Address toAddress = new InternetAddress (mailInfor. getMail_to (); // you can specify the recipient's Address.
Message. addRecipient (Message. RecipientType. TO, toAddress); // load the recipient address
 
Message. setText (mailInfor. getMail_body (); // you can specify the email body.
// Add each part of the email to the multipart object, including text content and attachments.
Multipart multipart = new MimeMultipart ();
// Set the text content of the email
BodyPart contentPart = new MimeBodyPart ();
ContentPart. setText (mailInfor. getMail_body ());
Multipart. addBodyPart (contentPart );
Multipart. addBodyPart (contentPart );
If (! MailInfor. getFile (). isEmpty () {// you have an attachment.
Enumeration efile = mailInfor. getFile (). elements ();
While (efile. hasMoreElements ()){
ContentPart = new MimeBodyPart ();
String filename = efile. nextElement (). toString (); // select the name of each attachment.
FileDataSource fds = new FileDataSource (filename); // obtain the data source
ContentPart. setDataHandler (new DataHandler (fds); // obtain the attachment and
// ContentPart. setFileName (fds. getName ());
//// Get the same file name to the BodyPart and solve the Chinese name garbled Problem
ContentPart. setFileName (MimeUtility. encodeText (fds
. GetName ()));
Multipart. addBodyPart (contentPart );
}
MailInfor. getFile (). removeAllElements ();
}
// Put the multipart object in the message
Message. setContent (multipart, "text/html; charset = gb2312"); // Add Multipart to a letter
// Save the email
Message. saveChanges ();
Transport. send (message); // send an email

System. out. println ("send OK! ");
 
} Catch (Exception ex ){
Ex. printStackTrace ();
Throw new Exception (ex. getMessage ());
}
}
 
/**
* Used for server-to-user authentication
*/
Class Email_Autherticator extends Authenticator {
Public Email_Autherticator (){
Super ();
}
Email_Autherticator (String user, String pwd ){
Super ();
MailInfor. setSendEmail (user );
MailInfor. setSendPassword (pwd );
}
Public PasswordAuthentication getPasswordAuthentication (){
Return new PasswordAuthentication (mailInfor. getSendEmail (),
MailInfor. getSendPassword ());
}
}
}
JavaBean
[Java]
Public class MailInformation {
// Email address server for sending emails
Private String host;
// This is your email account name and the email display sender's email address.
Private String sendEmail;
// Your email password
Private String sendPassword;
// Display the sender's name
Private String sendName;
// The email address to be received
Private String mail_to;
// Mail title
Private String mail_subject;
// Email content
Private String mail_body;
// A set of file names used to save attachments
Private Vector <String> file;
/**
* Input the sender's email information when creating an email entity
* @ Param sendEmail email address
* @ Param sendPassword: email Password
* @ Param sendName: the sender name is displayed in the sent email.
*/
Public MailInformation (String sendEmail, String sendPassword, String sendName ){
This. sendEmail = sendEmail;
This. sendPassword = sendName;
This. sendName = sendName;
}
/**
* Host in mailbox 163
*/
Public void set163Host (){
Host = "smtp.163.com ";
}
/**
* Host in mailbox 126
*/
Public void set126Host (){
Host = "smtp.126.com ";
}
/**
* Host of QQ mail
*/
Public void setQQHost (){
Host = "smtp.qq.com ";
}
/**
* Yahoo Mail host
*/
Public void setYahooHost (){
Host = "smtp.mail.yahoo.com.cn ";
}
/**
* Get the email address server for sending the mail
* @ Return address Server
*/
Public String getHost (){
Return host;
}
/**
* Set the email address server for sending emails
* @ Param host
*/
Public void setHost (String host ){
This. host = host;
}
/**
* Set the sender's email
* @ Param sendEmail email
*/
Public void setSendEmail (String sendEmail ){
This. sendEmail = sendEmail;
}
/**
* Get the sender's email
* @ Return sendEmail email
*/
Public String getSendEmail (){
Return sendEmail;
}
/**
* Set the sender's email password.
* @ Param sendPassword Password
*/
Public void setSendPassword (String sendPassword ){
This. sendPassword = sendPassword;
}
/**
* Get the sender's email password.
* @ Return sendPassword Password
*/
Public String getSendPassword (){
Return sendPassword;
}
/**
* Get the sender name displayed in the email
* @ Return sender name
*/
Public String getSendName (){
Return sendName;
}
/**
* Set the sender name displayed in the email.
* @ Param sendName sender name
*/
Public void setSendName (String sendName ){
This. sendName = sendName;
}
/**
* Get the recipient email
* @ Return recipient email
*/
Public String getMail_to (){
Return mail_to;
}
/**
* Set recipient email
* @ Param mail_to recipient email
*/
Public void setMail_to (String mail_to ){
This. mail_to = mail_to;
}
/**
* Mail title
* @ Return mail title
*/
Public String getMail_subject (){
Return mail_subject;
}
/**
* Set the mail title
* @ Param mail_subject: Mail title
*/
Public void setMail_subject (String mail_subject ){
This. mail_subject = mail_subject;
}
/**
* Get the email content
* @ Return mail content
*/
Public String getMail_body (){
Return mail_body;
}
/**
* Set email content
* @ Param mail_body content
*/
Public void setMail_body (String mail_body ){
This. mail_body = mail_body;
}
/**
* Obtain the absolute path of the attachment.
* @ Return absolute path
*/
Public Vector <String> getFile (){
Return file;
}
/**
* Absolute path of the tianjian attachment
* @ Return absolute path
*/
Public void setFile (Vector <String> file ){
This. file = file;
}
}
5. Call Method
[Java]
Public static void main (String [] args ){
SendMailService sendmail = SendMailService. getService ();
MailInformation mailInformation = new MailInformation (
"Sender email", "sender email password", "sender display name ");
MailInformation. set163Host ();
MailInformation. setMail_subject ("test email sending ");
MailInformation. setMail_body ("this is a test to test whether an email with an attachment can be sent ");
MailInformation. setSendEmail ("recipient email ");
Vector <String> fileStr = new Vector <String> ();
FileStr. add ("absolute path of attachment address ");
MailInformation. setFile (fileStr );
Sendmail. setMailInfor (mailInformation );
Try {
Sendmail. send ();
} Catch (Exception ex ){
Ex. printStackTrace ();
}
}

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.