Cum să trimiteți un e-mail utilizând Java MailAPI cu imagine mare ca atașament
Publicat: 2014-03-17API-ul JavaMail oferă un cadru independent de platformă și independent de protocol pentru a construi aplicații de e-mail și mesagerie. API-ul JavaMail este disponibil ca pachet opțional pentru utilizare cu platforma Java SE și este, de asemenea, inclus în platforma Java EE. Versiunea JavaMail 1.4.5 conține mai multe remedieri de erori și îmbunătățiri.
Cu ceva timp în urmă, am scris un tutorial despre Trimiterea unui e-mail utilizând Gmail SMTP (autentificare TLS), dar fără atașament de imagine. Tutorialul Java de mai jos vă va ajuta să trimiteți o imagine mare cu un e-mail ca atașament.
Uneori vrem să atașăm o imagine în e-mail și apoi să o folosim în corpul e-mailului. Trebuie să fi văzut atât de multe e-mailuri care au atașamente imagini și sunt folosite și în mesajul de e-mail. Trucul este să atașați fișierul imagine ca orice alt atașament și apoi să setați antetul Content-ID pentru fișierul imagine și apoi să utilizați același ID de conținut în corpul mesajului de e-mail cu <img src='cid:image_id'>
.
Iată un program Java simplu:
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 ( ) ; } } } |

Ieșire:
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 . . |
Exemplu de captură de ecran: