Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use JavaMail to send attachments

Shulou Source: shulou.com Published: 2022-06-02 03:41:46 10月03日 Update

This article mainly introduces the relevant knowledge of "how to send attachments with JavaMail". The editor shows you the operation process through an actual case. The method of operation is simple, fast and practical. I hope this article "how to use JavaMail to send attachments" can help you solve the problem.

Import Java.util.Properties

Import javax.Mail.*

Import javax.mail.inte.NET.*

Import javax.activation.*

Public class AttachExample {

Public static void main (String args [])

Throws Exception {

String host = args [0]

String from = args [1]

String to = args [2]

String fileAttachment = args [3]

/ / Get system properties

Properties props = System.getProperties ()

/ / Setup mail server

Props.put ("mail.smtp.host", host)

/ / Get session

Session session =

Session.getInstance (props, null)

/ / Define message

MimeMessage message =

New MimeMessage (session)

Message.setFrom (

New InternetAddress (from))

Message.addRecipient (

Message.RecipientType.TO

New InternetAddress (to))

Message.setSubject (

"Hello JavaMail Attachment")

/ / create the message part

MimeBodyPart messageBodyPart =

New MimeBodyPart ()

/ / fill message

MessageBodyPart.setText ("Hi")

Multipart multipart = new MimeMultipart ()

Multipart.addbodyPart (messageBodyPart)

/ / Part two is attachment

MessageBodyPart = new MimeBodyPart ()

Datasource source =

New FileDataSource (fileAttachment)

MessageBodyPart.setDataHandler (

New DataHandler (source))

MessageBodyPart.setFileName (fileAttachment)

Multipart.addBodyPart (messageBodyPart)

/ / Put parts in message

Message.setContent (multipart)

/ / Send the message

Transport.send (message)

}

}

This is the end of the content about "how to send attachments with JavaMail". Thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.

Tags: Attachments knowledge industries different practical content practical practical articles methods more cases knowledge points articles information channels processes problems channels Tiandu Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Huawei Microsoft MySQL Shulou Tech Info Apple