138.md 9.0 KB
Newer Older
W
wizardforcel 已提交
1
# 10 小时 高级 WebDriver – 发送带有附件的电子邮件
W
init  
wizardforcel 已提交
2 3 4

> 原文: [https://javabeginnerstutorial.com/selenium/10h-advanced-webdriver-sending-email-with-attachments/](https://javabeginnerstutorial.com/selenium/10h-advanced-webdriver-sending-email-with-attachments/)

W
wizardforcel 已提交
5
嗨冠军! 现在我们已经有了 [PDF 格式](https://javabeginnerstutorial.com/selenium/10e-advanced-webdriver-generating-pdf-report/)的 JUnit 报告,让我们将其附加到电子邮件中并发送给各个项目利益相关者。 因此,今天我们主要将仅使用 Java。 大家都来一杯咖啡(Java)!
W
init  
wizardforcel 已提交
6 7 8

我们将研究两个课程。

W
wizardforcel 已提交
9 10
1.  `SendMail.java` – 此类包含用于发送电子邮件的所有代码。
2.  `InvokeMail.java` – 通过提供从地址到地址,主题行和一些文本来调用`SendMail.java`
W
init  
wizardforcel 已提交
11

W
wizardforcel 已提交
12
## 代码
W
init  
wizardforcel 已提交
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 129 130 131 132

#### SendMail.java

```java
package com.blog.utility;

import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
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.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

/*
 * This class has the main code for sending mail
 */
public class SendMail {

  public static void send(String from, String tos[], String subject,
      String text) throws MessagingException {
    // Get the session object
    Properties props = new Properties();
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.socketFactory.port", "465");
    props.put("mail.smtp.socketFactory.class",
        "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.port", "465");

    Session session = Session.getDefaultInstance(props,
        new javax.mail.Authenticator() {
          protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(
            "[[email protected]](/cdn-cgi/l/email-protection)",
            "pass1234");// change accordingly
          }
        });

    // compose message
    try {
      MimeMessage message = new MimeMessage(session);
      message.setFrom(new InternetAddress(from));// change accordingly
      for (String to : tos) {
        message.addRecipient(Message.RecipientType.TO,
            new InternetAddress(to));
      }
      /*
       * for (String cc : ccs)
       * message.addRecipient(Message.RecipientType.CC,new
       * InternetAddress(cc));
       */
      message.setSubject(subject);
      // Option 1: To send normal text message
      // message.setText(text);
      // Option 2: Send the actual HTML message, as big as you like
      // message.setContent("<h1>This is actual message</h1></br></hr>" +
      // text, "text/html");

      // Set the attachment path
      String filename = "E:\\Selenium\\junit.pdf";

      BodyPart objMessageBodyPart = new MimeBodyPart();
      // Option 3: Send text along with attachment
      objMessageBodyPart.setContent(
          "<h1>Mail from Selenium Project!</h1></br>" + text, "text/html");
      Multipart multipart = new MimeMultipart();
      multipart.addBodyPart(objMessageBodyPart);

      objMessageBodyPart = new MimeBodyPart();
      DataSource source = new FileDataSource(filename);
      objMessageBodyPart.setDataHandler(new DataHandler(source));
      objMessageBodyPart.setFileName(filename);
      multipart.addBodyPart(objMessageBodyPart);
      message.setContent(multipart);

      // send message
      Transport.send(message);

      System.out.println("message sent successfully");

    } catch (MessagingException e) {
      throw new RuntimeException(e);
    }
  }// End of SEND method
}
```

#### InvokeMail.java

```java
package com.blog.junitTests;

import javax.mail.MessagingException;
import com.blog.utility.SendMail;

/*
 * Invokes SendMail.java 
 */
public class InvokeMail {
  public static void main(String[] args) throws MessagingException {

    //String to[] = {"[[email protected]](/cdn-cgi/l/email-protection)","[[email protected]](/cdn-cgi/l/email-protection)"};
    String to[] = {"[[email protected]](/cdn-cgi/l/email-protection)"};

    SendMail.send("[[email protected]](/cdn-cgi/l/email-protection)", to, "JUnit Report", "Check the PDF attachment.");		

  }
}
```

W
wizardforcel 已提交
133
## 解释
W
init  
wizardforcel 已提交
134 135 136

直接看一下代码会使我们感到难以接受。 让我们一次了解一个摘要。

W
wizardforcel 已提交
137
与往常一样,我们的第一步是下载几个 JAR。
W
init  
wizardforcel 已提交
138 139 140 141

1.  activation.jar
2.  javax.mail-1.6.1.jar

W
wizardforcel 已提交
142
我还将它们都放在了我们的 [**GitHub 仓库**](https://github.com/JBTAdmin/Selenium/tree/master/AdvancedWebDriver/Sending%20Email)中,以及作为本文一部分处理的所有其他代码文件中。
W
init  
wizardforcel 已提交
143

W
wizardforcel 已提交
144
将这些 JAR 添加到我们的项目构建路径中。 我们之前已经多次看到此程序,因此我不再重复(有关详细说明,请参阅此[文章](https://javabeginnerstutorial.com/selenium/9b-webdriver-eclipse-setup/)的步骤 3)。
W
init  
wizardforcel 已提交
145

W
wizardforcel 已提交
146
### 了解`SendMail.java`,
W
init  
wizardforcel 已提交
147 148 149 150 151 152 153 154

1.编写所有代码的方法,以便我们可以从任何类轻松地调用它。

```java
public static void send(String from, String tos[], String subject,
      String text) throws MessagingException {}
```

W
wizardforcel 已提交
155
2.给定的属性仅适用于 Gmail。 如果您根据项目要求使用 Outlook 或任何其他服务,则应相应地进行更改。
W
init  
wizardforcel 已提交
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206

```java
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class",
  "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
```

3.获取会话对象并传递您的电子邮件帐户的凭据(您在地址中提到的凭据)。

```java
Session session = Session.getDefaultInstance(props,
        new javax.mail.Authenticator() {
    protected PasswordAuthentication getPasswordAuthentication() {
  return new PasswordAuthentication("[[email protected]](/cdn-cgi/l/email-protection)","pass1234");// change accordingly
    }
}); 
```

4.现在是有趣的部分。 我们将指定“发件人”和“收件人”地址。

```java
message.setFrom(new InternetAddress(from));
for (String to : tos) {
    message.addRecipient(Message.RecipientType.TO,
    new InternetAddress(to));
  } 
```

如果您只想将此电子邮件发送给一个人,请更改以下代码,

```java
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO,
    new InternetAddress(to));
```

如果您希望将其发送给抄送给某些人的用户,请按以下所示更改代码,

```java
message.addRecipient(Message.RecipientType.CC,new InternetAddress(cc));
```

5.将主题行设置为`message.setSubject(subject);`

6.要发送,

*   普通短信`message.setText(text);`
W
wizardforcel 已提交
207
*   实际的 HTML 消息尽可能多`message.setContent("<h1>This is actual message</h1></br></hr>" + text, "text/html");`
W
init  
wizardforcel 已提交
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
*   文本和附件(这就是我们想要的),

```java
// Set the attachment path
String filename = "E:\\Selenium\\junit.pdf";
BodyPart objMessageBodyPart = new MimeBodyPart();
objMessageBodyPart.setContent("<h1>Mail from Selenium Project!</h1></br>" + text, "text/html");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(objMessageBodyPart);
objMessageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(filename);
objMessageBodyPart.setDataHandler(new DataHandler(source));
objMessageBodyPart.setFileName(filename);
multipart.addBodyPart(objMessageBodyPart);
message.setContent(multipart);
```

7.用简单的一行发送电子邮件,

```java
Transport.send(message);
```

W
wizardforcel 已提交
231
### 了解`InvokeMail.java`,
W
init  
wizardforcel 已提交
232

W
wizardforcel 已提交
233
此类很容易理解,因为我们只是通过提供所有必需的参数从`SendMail.java`调用“`send`”方法。
W
init  
wizardforcel 已提交
234 235 236 237 238 239

```java
String to[] = {"[[email protected]](/cdn-cgi/l/email-protection)"};
SendMail.send("[[email protected]](/cdn-cgi/l/email-protection)", to, "JUnit Report", "Check the PDF attachment.");
```

W
wizardforcel 已提交
240
在“运行方式-> Java 应用”下,Eclipse IDE 控制台的输出如下所示,
W
init  
wizardforcel 已提交
241

W
wizardforcel 已提交
242
![Email eclipse console output](img/f86911f5f3e724f4f0f756b02cbb24e2.png)
W
init  
wizardforcel 已提交
243

W
wizardforcel 已提交
244 245 246 247 248 249 250 251 252 253 254 255 256
该电子邮件将在收件人的收件箱中接收。

![Email received in Inbox](img/dc54350168b4d2d375448a69dcdf1262.png)

显示生成的带有附件的电子邮件,以供您参考。

![Generated email](img/ec66e3d16d437df63174e68a50e156cb.png)

**注意:** *当心! 您可能碰到“`javax.mail.AuthenticationFailedException`”。 发生此异常的主要原因是 Google 提供的安全性和保护功能。 一种简单的解决方法是,通过单击链接 [https://www.google.com/settings/security/lesssecureapps](https://www.google.com/settings/security/lesssecureapps) 来打开“允许安全程度较低的应用”的访问以进行测试。*

试试看,让我知道在拍摄电子邮件时是否遇到任何问题。

实验愉快! 祝你今天愉快!