Comment envoyer un e-mail à l'aide de Java MailAPI avec une grande image en pièce jointe
Publié: 2014-03-17L'API JavaMail fournit un cadre indépendant de la plate-forme et du protocole pour créer des applications de messagerie et de messagerie. L'API JavaMail est disponible en tant que package facultatif à utiliser avec la plate-forme Java SE et est également incluse dans la plate-forme Java EE. La version JavaMail 1.4.5 contient plusieurs corrections de bogues et améliorations.
Il y a quelque temps, j'ai écrit un didacticiel sur Envoyer un e-mail à l'aide de Gmail SMTP (authentification TLS), mais sans pièce jointe d'image. Le didacticiel Java ci-dessous vous aidera à envoyer une grande image avec un e-mail en pièce jointe.
Parfois, nous souhaitons joindre une image dans l'e-mail, puis l'utiliser dans le corps de l'e-mail lui-même. Vous devez avoir vu tant d'e-mails contenant des images jointes et qui sont également utilisés dans le message électronique. L'astuce consiste à joindre le fichier image comme toute autre pièce jointe, puis à définir l'en-tête Content-ID pour le fichier image, puis à utiliser le même identifiant de contenu dans le corps du message électronique avec <img src='cid:image_id'>
.
Voici un programme Java simple :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 |
package com . crunchify . tutorials ; import java . io . UnsupportedEncodingException ; import java . util . Date ; import java . util . Properties ; import javax . activation . DataHandler ; import javax . activation . DataSource ; import javax . activation . FileDataSource ; import javax . mail . Authenticator ; import javax . mail . BodyPart ; import javax . mail . Message ; import javax . mail . MessagingException ; import javax . mail . Multipart ; import javax . mail . PasswordAuthentication ; 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 ; /** * @author Crunchify.com * */ public class CrunchifyJavaMailWithImageAttachment { static Properties mailServerProperties ; static Session getMailSession ; static MimeMessage msg ; public static void main ( String args [ ] ) throws AddressException , MessagingException { System . out . println ( "\n1st ===> setup Mail Server Properties.." ) ; final String sourceEmail = "<Your Gmail Email ID" ; // requires valid Gmail id final String password = "Your Gmail Password" ; // correct password for Gmail id Properties props = new Properties ( ) ; props . put ( "mail.smtp.host" , "smtp.gmail.com" ) ; props . put ( "mail.smtp.port" , "587" ) ; props . put ( "mail.smtp.auth" , "true" ) ; props . put ( "mail.smtp.starttls.enable" , "true" ) ; System . out . println ( "\n2nd ===> create Authenticator object to pass in Session.getInstance argument.." ) ; Authenticator authentication = new Authenticator ( ) { protected PasswordAuthentication getPasswordAuthentication ( ) { return new PasswordAuthentication ( sourceEmail , password ) ; } } ; Session session = Session . getInstance ( props , authentication ) ; generateAndSendEmail ( session , toEmail , "Crunchify's JavaMail API example with Image Attachment" , "Greetings, <br><br>Test email by Crunchify.com JavaMail API example. Please find here attached Image." + "<br><br> Regards, <br>Crunchify Admin" ) ; } public static void generateAndSendEmail ( Session session , String toEmail , String subject , String body ) { try { System . out . println ( "\n3rd ===> generateAndSendEmail() starts.." ) ; MimeMessage crunchifyMessage = new MimeMessage ( session ) ; crunchifyMessage . addHeader ( "Content-type" , "text/HTML; charset=UTF-8" ) ; crunchifyMessage . addHeader ( "format" , "flowed" ) ; crunchifyMessage . addHeader ( "Content-Transfer-Encoding" , "8bit" ) ; "NoReply-Crunchify" ) ) ; crunchifyMessage . setSubject ( subject , "UTF-8" ) ; crunchifyMessage . setSentDate ( new Date ( ) ) ; crunchifyMessage . setRecipients ( Message . RecipientType . TO , InternetAddress . parse ( toEmail , false ) ) ; // Create the message body part BodyPart messageBodyPart = new MimeBodyPart ( ) ; messageBodyPart . setContent ( body , "text/html" ) ; // Create a multipart message for attachment Multipart multipart = new MimeMultipart ( ) ; // Set text message part multipart . addBodyPart ( messageBodyPart ) ; messageBodyPart = new MimeBodyPart ( ) ; // Valid file location String filename = "/Users/<username>//cdn.crunchify.com/Desktop/JavaMailAPIwithImage-CrunchifyExample.png" ; DataSource source = new FileDataSource ( filename ) ; messageBodyPart . setDataHandler ( new DataHandler ( source ) ) ; messageBodyPart . setFileName ( filename ) ; // Trick is to add the content-id header here messageBodyPart . setHeader ( "Content-ID" , "image_id" ) ; multipart . addBodyPart ( messageBodyPart ) ; System . out . println ( "\n4th ===> third part for displaying image in the email body.." ) ; messageBodyPart = new MimeBodyPart ( ) ; messageBodyPart . setContent ( "<br><h3>Find below attached image</h3>" + "<img src='cid:image_id'>" , "text/html" ) ; multipart . addBodyPart ( messageBodyPart ) ; crunchifyMessage . setContent ( multipart ) ; System . out . println ( "\n5th ===> Finally Send message.." ) ; // Finally Send message Transport . send ( crunchifyMessage ) ; System . out . println ( "\n6th ===> Email Sent Successfully With Image Attachment. Check your email now.." ) ; System . out . println ( "\n7th ===> generateAndSendEmail() ends.." ) ; } catch ( MessagingException e ) { e . printStackTrace ( ) ; } catch ( UnsupportedEncodingException e ) { e . printStackTrace ( ) ; } } } |

Sortir:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
1st === > setup Mail Server Properties . . 2nd === > create Authenticator object to pass in Session . getInstance argument . . 3rd === > generateAndSendEmail ( ) starts . . 4th === > third part for displaying image in the email body . . 5th === > Finally Send message . . 6th === > Email Sent Successfully With Image Attachment . Check your email now . . 7th === > generateAndSendEmail ( ) ends . . |
Exemple de capture d'écran :