Classes involved in creating a message: MimeMessage, MimeBodyPart, Mimemultipart
Classes involved in sending mail: Transport
Related classes: Session, Properties
Instance:
/*** Make an email with an attachment and send it * *@throwsException*/ Public Static voidMakeemailandsend ()throwsException {String from= "";//Outgoing outboxString to = "";//InboxString subject = "Test";//Message SubjectString BODY = "TestResult";//Message Content//mail server address and login username and passwordString SMTPHost = ""; String User= ""; String Password= ""; Properties Props=NewProperties ();//Properties User Property configurationProps.setproperty ("Mail.transport.protocol", "SMTP");//protocol Used (JavaMail specification requirements)Props.setproperty ("Mail.smtp.host", SMTPHost);//SMTP server address for sender's mailboxProps.setproperty ("Mail.smtp.auth", "true");//request authentication, parameter names are related to the specific implementationSession Session= Session.getdefaultinstance (props);//session objects are primarily used for attribute operations and session management//Create a MimeMessage object that defines the MIME message header informationMimeMessage message =NewMimeMessage (session); Message.setfrom (Newinternetaddress (from)); Message.setrecipients (MimeMessage.RecipientType.TO, to); Message.setsubject (subject); Message.setsentdate (NewDate ());//Message.settext (body);//Send plain text mail, can be directly used SetText//defines a Mimemultipart object that can contain multiple MimeBodyPartMimemultipart multipart =NewMimemultipart (); //represents a MIME message for a messageMimeBodyPart BodyPart =NewMimeBodyPart (); Bodypart.setcontent (Body,"Text/html;charset=utf-8");//set the message body in HTML formatMultipart.addbodypart (bodypart); //Create an MimeBodyPart object of an attachment and add it to the Mimemultipart object you created earlierMimeBodyPart attachment =NewMimeBodyPart (); Filedatasource DataSource=NewFiledatasource ("D:\\test.jpg"); Attachment.setfilename (Datasource.getname ()); Attachment.setdatahandler (NewDataHandler (DataSource)); Multipart.addbodypart (attachment); //to add a multipart object to the body of a messagemessage.setcontent (multipart); Message.savechanges ();//save and generate message content//initializes the transport with the Gettransport method of the JavaMail session objectTransport Transport = Session.gettransport ("SMTP"); Transport.connect (smtphost, user, password); //Send, message.getallrecipients () gets all the recipients that were added when the message object was created, Cc, BCC .transport.sendmessage (Message, message.getallrecipients ()); Transport.close (); }
Java creates a message and sends