Bonjour,
je voudrai envoyer un fichier joint par email en java.
J'ai une classe SendFile et une classe Test.
Le nom du fichier est specifié dans la class Test et utilise la classe SendFile pour envoyer le fichier.
Ce que je n'arrive pas a faire:
c'est recuperer le fichier de la classe Test dans la classe SendFile.
Merci
SendFile.java
Test.java
Code : Sélectionner tout - Visualiser dans une fenêtre à part
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 public class SendFile { private static String[] args; public static void sendEmail(File filetosend) throws IOException, Exception{ //public static void main(String[] args) throws IOException { final String username = "email0@gmail.com"; final String password = "password"; Properties props = new Properties(); props.put("mail.smtp.auth", true); props.put("mail.smtp.starttls.enable", true); props.put("mail.smtp.host", "smtp.gmail.com"); props.put("mail.smtp.port", "587"); Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress("email0@gmail.com")); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("email0@gmail.com")); message.setSubject("Attach file Test from Netbeans"); message.setText("PFA"); MimeBodyPart messageBodyPart = new MimeBodyPart(); Multipart multipart = new MimeMultipart(); messageBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(filetosend); System.out.println("The filetosend is ="+filetosend); messageBodyPart.setDataHandler(new DataHandler(source)); System.out.println("The source is ="+source); messageBodyPart.attachFile(filetosend); System.out.println("The file name is ="+messageBodyPart.getFileName()); multipart.addBodyPart(messageBodyPart); System.out.println("The message body part is ="+messageBodyPart); message.setContent(multipart); System.out.println("The message multi part is ="+multipart); System.out.println("Sending"); Transport.send(message); System.out.println("The message is ="+message); System.out.println("Done"); } catch (MessagingException e) { e.printStackTrace(); } } }
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 import java.io.File; import java.io.IOException; public class Test { public static void main(String[] args) throws Exception { } File file; public void Test() throws IOException, Exception{ System.out.println("Sending the file..."); File filetosend = new File("c:\\file.txt"); SendFile.sendEmail(filetosend); } }
Partager