这篇文章主要围绕如何强制JavaMailSenderImpl使用TLS1.2?和java强行展开,旨在为您提供一份详细的参考资料。我们将全面介绍如何强制JavaMailSenderImpl使用TLS1
这篇文章主要围绕如何强制JavaMailSenderImpl使用TLS1.2?和java强行展开,旨在为您提供一份详细的参考资料。我们将全面介绍如何强制JavaMailSenderImpl使用TLS1.2?的优缺点,解答java强行的相关问题,同时也会为您带来com.amazonaws.services.simpleemail.AmazonSimpleEmailServiceClientBuilder的实例源码、com.amazonaws.services.simpleemail.AmazonSimpleEmailServiceClient的实例源码、com.amazonaws.services.simpleemail.AmazonSimpleEmailService的实例源码、JavaMailSenderImpl的实用方法。
本文目录一览:- 如何强制JavaMailSenderImpl使用TLS1.2?(java强行)
- com.amazonaws.services.simpleemail.AmazonSimpleEmailServiceClientBuilder的实例源码
- com.amazonaws.services.simpleemail.AmazonSimpleEmailServiceClient的实例源码
- com.amazonaws.services.simpleemail.AmazonSimpleEmailService的实例源码
- JavaMailSenderImpl
如何强制JavaMailSenderImpl使用TLS1.2?(java强行)
有一个在Tomcat上运行的JDK7应用程序,它具有以下环境设置:
-Dhttps.protocols=TLSv1.1,TLSv1.2
上面的设置可确保在进行API调用等操作时通过HTTPS连接时不使用TLS 1.0。
我们还使用org.springframework.mail.javamail。 JavaMailSenderImpl
类发送外发SMTP电子邮件,并使用以下道具:
mail.smtp.auth=false;mail.smtp.socketFactory.port=2525;mail.smtp.socketFactory.fallback=true;mail.smtp.starttls.enable=true
问题是,当升级到TLS1.2时,与SMTP电子邮件服务器的连接失败。
javax.net.ssl.SSLHandshakeException:握手期间远程主机关闭连接
是否有设置或代码更改会强制使用TLS1.2协议?
我做了一些搜索,看来这些环境设置仅适用于applet和Web客户端,不适用于服务器端应用程序
-Ddeployment.security.SSLv2Hello=false -Ddeployment.security.SSLv3=false -Ddeployment.security.TLSv1=false
答案1
小编典典这是寻找下一个家伙的解决方法:
mail.smtp.starttls.enable=true;mail.smtp.ssl.protocols=TLSv1.2;
com.amazonaws.services.simpleemail.AmazonSimpleEmailServiceClientBuilder的实例源码
@Override void makeSend(String to,String subject,String msg) { String accessKey = config.readString(ConfigProperty.SES_ACCESS_KEY); String secretKey = config.readString(ConfigProperty.SES_SECRET_KEY); if (!Strings.isNullOrEmpty(accessKey)) { Destination destination = new Destination().withToAddresses(to); Content subj = new Content().withData(subject); Content textBody = new Content().withData(msg); Body body = new Body().withHtml(textBody); Message message = new Message().withSubject(subj).withBody(body); SendEmailRequest req = new SendEmailRequest().withSource(config.readString(ConfigProperty.EMAIL_DEFAULT_FROM_NAME) + " <" + config.readString(ConfigProperty.EMAIL_DEFAULT_FROM) + ">") .withDestination(destination).withMessage(message); AmazonSimpleEmailService client = AmazonSimpleEmailServiceClientBuilder.standard() .withRegion(config.readString(ConfigProperty.SES_REGION)) .withCredentials(new AWsstaticCredentialsProvider(new BasicAWSCredentials(accessKey,secretKey))) .build(); try { client.sendEmail(req); } finally { client.shutdown(); } } else { throw new IllegalStateException("SES Mail provider wasn't configured well."); } }
@postconstruct public void afterPropertiesSet() { AWSCredentials awsSesCredentials = new BasicAWSCredentials(mailProperties.getAwsAccessKey(),mailProperties.getAwsSecretKey()); this.client = AmazonSimpleEmailServiceClientBuilder.standard() .withRegion(Regions.US_EAST_1) .withCredentials(new AWsstaticCredentialsProvider(awsSesCredentials)) .build(); logger.info("mail agent ready,sender:" + mailProperties.getAwsSenderAddress() + ",access key:" + awsSesCredentials.getAWSAccessKeyId()); }
public static AmazonSimpleEmailServiceClient createEmailClient() { BasicCredentialsProvider credentials = BasicCredentialsProvider.standard(); AmazonSimpleEmailServiceClient client = !credentials.isValid() ? null : (AmazonSimpleEmailServiceClient) AmazonSimpleEmailServiceClientBuilder.standard() .withCredentials(credentials) .withRegion("eu-west-1") .build(); return client; }
@Override public Parameters handleRequest(Parameters parameters,Context context) { context.getLogger().log("Input Function [" + context.getFunctionName() + "],Parameters [" + parameters + "]"); try { // Create an empty Mime message and start populating it Session session = Session.getDefaultInstance(new Properties()); MimeMessage message = new MimeMessage(session); message.setSubject(EMAIL_SUBJECT,"UTF-8"); message.setFrom(new InternetAddress(System.getenv("EMAIL_FROM"))); message.setReplyTo(new Address[] { new InternetAddress(System.getenv("EMAIL_FROM")) }); message.setRecipients(Message.RecipientType.TO,InternetAddress.parse(System.getenv("EMAIL_RECIPIENT"))); MimeBodyPart wrap = new MimeBodyPart(); MimeMultipart cover = new MimeMultipart("alternative"); MimeBodyPart html = new MimeBodyPart(); cover.addBodyPart(html); wrap.setContent(cover); MimeMultipart content = new MimeMultipart("related"); message.setContent(content); content.addBodyPart(wrap); // Create an S3 URL reference to the snapshot that will be attached to this email URL attachmentURL = createSignedURL(parameters.getS3Bucket(),parameters.getS3Key()); StringBuilder sb = new StringBuilder(); String id = UUID.randomUUID().toString(); sb.append("<img src=\"cid:"); sb.append(id); sb.append("\" alt=\"ATTACHMENT\"/>\n"); // Add the attachment as a part of the message body MimeBodyPart attachment = new MimeBodyPart(); DataSource fds = new URLDataSource(attachmentURL); attachment.setDataHandler(new DataHandler(fds)); attachment.setContentID("<" + id + ">"); attachment.setdisposition(BodyPart.ATTACHMENT); attachment.setFileName(fds.getName()); content.addBodyPart(attachment); // Pretty print the Rekognition Labels as part of the Emails HTML content String prettyPrintLabels = parameters.getRekognitionLabels().toString(); prettyPrintLabels = prettyPrintLabels.replace("{","").replace("}",""); prettyPrintLabels = prettyPrintLabels.replace(",","<br>"); html.setContent("<html><body><h2>Uploaded Filename : " + parameters.getS3Key().replace("upload/","") + "</h2><p><b>Detected Labels/Confidence</b><br><br>" + prettyPrintLabels + "</p>"+sb+"</body></html>","text/html"); // Convert the JavaMail message into a raw email request for sending via SES ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); message.writeto(outputStream); RawMessage rawMessage = new RawMessage(ByteBuffer.wrap(outputStream.toByteArray())); SendRawEmailRequest rawEmailRequest = new SendRawEmailRequest(rawMessage); // Send the email using the AWS SES Service AmazonSimpleEmailService client = AmazonSimpleEmailServiceClientBuilder.defaultClient(); client.sendRawEmail(rawEmailRequest); } catch (MessagingException | IOException e) { // Convert Checked Exceptions to RuntimeExceptions to ensure that // they get picked up by the Step Function infrastructure throw new AmazonServiceException("Error in ["+context.getFunctionName()+"]",e); } context.getLogger().log("Output Function [" + context.getFunctionName() + "],Parameters [" + parameters + "]"); return parameters; }
/** * No-args constructor. */ public AWSEmailer() { sesclient = AmazonSimpleEmailServiceClientBuilder.standard().withCredentials(new AWsstaticCredentialsProvider( new BasicAWSCredentials(Config.AWS_ACCESSKEY,Config.AWS_SECRETKEY))). withRegion(Config.AWS_REGION).build(); }
com.amazonaws.services.simpleemail.AmazonSimpleEmailServiceClient的实例源码
/** * Inits the. */ public void init() { if (this.awsAccessKey == null) { this.awsAccessKey = System.getenv("AWS_ACCESS_KEY"); if (this.awsAccessKey == null) { this.awsAccessKey = System.getProperty("com.oneops.aws.accesskey"); } } if (this.awsSecretKey == null) { this.awsSecretKey = System.getenv("AWS_SECRET_KEY"); if (this.awsSecretKey == null) { this.awsSecretKey = System.getProperty("com.oneops.aws.secretkey"); } } emailClient = new AmazonSimpleEmailServiceClient( new BasicAWSCredentials(awsAccessKey,awsSecretKey)); }
private void sendSimpleMail(List<String> to,List<String> cc,List<String> ci,String object,String content,boolean htmlContent) { Destination destination = new Destination().withToAddresses(to).withBccAddresses(ci).withCcAddresses(cc); Content subject = new Content().withData(object); Content bodyContent = new Content().withData(content); Body body; if (htmlContent) { body = new Body().withHtml(bodyContent); } else { body = new Body().withText(bodyContent); } Message message = new Message().withSubject(subject).withBody(body); SendEmailRequest request = new SendEmailRequest().withSource(from).withDestination(destination).withMessage(message); try { AmazonSimpleEmailServiceClient client = new AmazonSimpleEmailServiceClient(); client.setRegion(region); client.sendEmail(request); } catch (Exception e) { LOGGER.error("Unable to send email to {} with subject '{}'",StringUtils.join(to,","),subject,e); } }
public static void emailVerification(String name,String email,UUID uuid,String username,String responseServletUrl,ServletConfig config) throws EmailUtilException { String fromEmail = config.getServletContext().ge@R_301_6182@tParameter("return_email"); if (fromEmail == null || fromEmail.isEmpty()) { logger.error("Missing return_email parameter in the web.xml file"); throw(new EmailUtilException("The from email for the email facility has not been set. Pleaese contact the OpenChain team with this error.")); } String link = responseServletUrl + "?request=register&username=" + username + "&uuid=" + uuid.toString(); StringBuilder msg = new StringBuilder("<div>Welcome "); msg.append(name); msg.append(" to the OpenChain Certification website.<br /> <br />To complete your registration,click on the following or copy/paste into your web browser <a href=\""); msg.append(link); msg.append("\">"); msg.append(link); msg.append("</a><br/><br/>Thanks,<br/>The OpenChain team</div>"); Destination destination = new Destination().withToAddresses(new String[]{email}); Content subject = new Content().withData("OpenChain Registration [do not reply]"); Content bodyData = new Content().withData(msg.toString()); Body body = new Body(); body.setHtml(bodyData); Message message = new Message().withSubject(subject).withBody(body); SendEmailRequest request = new SendEmailRequest().withSource(fromEmail).withDestination(destination).withMessage(message); try { AmazonSimpleEmailServiceClient client = getEmailClient(config); client.sendEmail(request); logger.info("Invitation email sent to "+email); } catch (Exception ex) { logger.error("Email send Failed",ex); throw(new EmailUtilException("Exception occured during the emailing of the invitation",ex)); } }
@SuppressWarnings("unused") private static void logMailInfo(AmazonSimpleEmailServiceClient client,ServletConfig config) { logger.info("Email Service Name: "+client.getServiceName()); List<String> identities = client.listIdentities().getIdentities(); for (String identity:identities) { logger.info("Email identity: "+identity); } List<String> verifiedEmails = client.listVerifiedEmailAddresses().getVerifiedEmailAddresses(); for (String email:verifiedEmails) { logger.info("Email verified email address: "+email); } GetSendQuotaResult sendQuota = client.getSendQuota(); logger.info("Max 24 hour send="+sendQuota.getMax24HourSend()+",Max Send Rate="+ sendQuota.getMaxSendrate() + ",Sent last 24 hours="+sendQuota.getSentLast24Hours()); }
public static void emailUser(String toEmail,String subjectText,String msg,ServletConfig config) throws EmailUtilException { String fromEmail = config.getServletContext().ge@R_301_6182@tParameter("return_email"); if (fromEmail == null || fromEmail.isEmpty()) { logger.error("Missing return_email parameter in the web.xml file"); throw(new EmailUtilException("The from email for the email facility has not been set. Pleaese contact the OpenChain team with this error.")); } if (toEmail == null || toEmail.isEmpty()) { logger.error("Missing notification_email parameter in the web.xml file"); throw(new EmailUtilException("The to email for the email facility has not been set. Pleaese contact the OpenChain team with this error.")); } Destination destination = new Destination().withToAddresses(new String[]{toEmail}); Content subject = new Content().withData(subjectText); Content bodyData = new Content().withData(msg.toString()); Body body = new Body(); body.setHtml(bodyData); Message message = new Message().withSubject(subject).withBody(body); SendEmailRequest request = new SendEmailRequest().withSource(fromEmail).withDestination(destination).withMessage(message); try { AmazonSimpleEmailServiceClient client = getEmailClient(config); client.sendEmail(request); logger.info("User email sent to "+toEmail+": "+msg); } catch (Exception ex) { logger.error("Email send Failed",ex); throw(new EmailUtilException("Exception occured during the emailing of a user email",ex)); } }
public static void emailAdmin(String subjectText,ServletConfig config) throws EmailUtilException { String fromEmail = config.getServletContext().ge@R_301_6182@tParameter("return_email"); if (fromEmail == null || fromEmail.isEmpty()) { logger.error("Missing return_email parameter in the web.xml file"); throw(new EmailUtilException("The from email for the email facility has not been set. Pleaese contact the OpenChain team with this error.")); } String toEmail = config.getServletContext().ge@R_301_6182@tParameter("notification_email"); if (toEmail == null || toEmail.isEmpty()) { logger.error("Missing notification_email parameter in the web.xml file"); throw(new EmailUtilException("The to email for the email facility has not been set. Pleaese contact the OpenChain team with this error.")); } Destination destination = new Destination().withToAddresses(new String[]{toEmail}); Content subject = new Content().withData(subjectText); Content bodyData = new Content().withData(msg.toString()); Body body = new Body(); body.setHtml(bodyData); Message message = new Message().withSubject(subject).withBody(body); SendEmailRequest request = new SendEmailRequest().withSource(fromEmail).withDestination(destination).withMessage(message); try { AmazonSimpleEmailServiceClient client = getEmailClient(config); client.sendEmail(request); logger.info("Admin email sent to "+toEmail+": "+msg); } catch (Exception ex) { logger.error("Email send Failed",ex); throw(new EmailUtilException("Exception occured during the emailing of the submission notification",ex)); } }
/** * Email to notify a user that their profiles was updated * @param username * @param email * @param config * @throws EmailUtilException */ public static void emailProfileUpdate(String username,ServletConfig config) throws EmailUtilException { String fromEmail = config.getServletContext().ge@R_301_6182@tParameter("return_email"); if (fromEmail == null || fromEmail.isEmpty()) { logger.error("Missing return_email parameter in the web.xml file"); throw(new EmailUtilException("The from email for the email facility has not been set. Pleaese contact the OpenChain team with this error.")); } StringBuilder msg = new StringBuilder("<div>The profile for username "); msg.append(username); msg.append(" has been updated. If you this update has been made in error,please contact the OpenChain certification team."); Destination destination = new Destination().withToAddresses(new String[]{email}); Content subject = new Content().withData("OpenChain Certification profile updated [do not reply]"); Content bodyData = new Content().withData(msg.toString()); Body body = new Body(); body.setHtml(bodyData); Message message = new Message().withSubject(subject).withBody(body); SendEmailRequest request = new SendEmailRequest().withSource(fromEmail).withDestination(destination).withMessage(message); try { AmazonSimpleEmailServiceClient client = getEmailClient(config); client.sendEmail(request); logger.info("Notification email sent for "+email); } catch (Exception ex) { logger.error("Email send Failed",ex)); } }
public static void emailPasswordReset(String name,ServletConfig config) throws EmailUtilException { String fromEmail = config.getServletContext().ge@R_301_6182@tParameter("return_email"); if (fromEmail == null || fromEmail.isEmpty()) { logger.error("Missing return_email parameter in the web.xml file"); throw(new EmailUtilException("The from email for the email facility has not been set. Pleaese contact the OpenChain team with this error.")); } String link = responseServletUrl + "?request=pwreset&username=" + username + "&uuid=" + uuid.toString(); StringBuilder msg = new StringBuilder("<div>To reset the your password,click on the following or copy/paste into your web browser <a href=\""); msg.append(link); msg.append("\">"); msg.append(link); msg.append("</a><br/><br/><br/>The OpenChain team</div>"); Destination destination = new Destination().withToAddresses(new String[]{email}); Content subject = new Content().withData("OpenChain Password Reset [do not reply]"); Content bodyData = new Content().withData(msg.toString()); Body body = new Body(); body.setHtml(bodyData); Message message = new Message().withSubject(subject).withBody(body); SendEmailRequest request = new SendEmailRequest().withSource(fromEmail).withDestination(destination).withMessage(message); try { AmazonSimpleEmailServiceClient client = getEmailClient(config); client.sendEmail(request); logger.info("Reset password email sent to "+email); } catch (Exception ex) { logger.error("Email send Failed",ex); throw(new EmailUtilException("Exception occured during the emailing of the password reset",ex)); } }
private void initClients() { AWSCredentials credentials = AmazonSharedPreferencesWrapper .getCredentialsFromSharedPreferences(this.sharedPreferences); Region region = Region.getRegion(Regions.US_EAST_1); sesClient = new AmazonSimpleEmailServiceClient(credentials); sesClient.setRegion(region); }
public EmailWebServiceTask( Context context ) { String accessKey = context.getString(R.string.aws_access_key); String secretKey = context.getString(R.string.aws_secret_key); fromVerifiedAddress = context.getString(R.string.aws_verified_address); toAddress = getAccountEmail( context ); AWSCredentials credentials = new BasicAWSCredentials(accessKey,secretKey); sesClient = new AmazonSimpleEmailServiceClient( credentials ); }
@Test public void parse_MailSenderWithMinimalConfiguration_createMailSenderWithJavaMail() throws Exception { //Arrange ClasspathXmlApplicationContext context = new ClasspathXmlApplicationContext(getClass().getSimpleName() + "-context.xml",getClass()); //Act AmazonSimpleEmailServiceClient emailService = context.getBean(getBeanName(AmazonSimpleEmailServiceClient.class.getName()),AmazonSimpleEmailServiceClient.class); MailSender mailSender = context.getBean(MailSender.class); //Assert assertEquals("https://email.us-west-2.amazonaws.com",getEndpointUrlFromWebserviceClient(emailService)); assertTrue(mailSender instanceof JavaMailSender); }
@Test public void parse_MailSenderWithRegionConfiguration_createMailSenderWithJavaMailAndRegion() throws Exception { //Arrange ClasspathXmlApplicationContext context = new ClasspathXmlApplicationContext(getClass().getSimpleName() + "-region.xml",AmazonSimpleEmailServiceClient.class); MailSender mailSender = context.getBean(MailSender.class); //Assert assertEquals("https://email.eu-west-1.amazonaws.com",getEndpointUrlFromWebserviceClient(emailService)); assertTrue(mailSender instanceof JavaMailSender); }
@Test public void parse_MailSenderWithRegionProviderConfiguration_createMailSenderWithJavaMailAndRegionFromregionProvider() throws Exception { //Arrange ClasspathXmlApplicationContext context = new ClasspathXmlApplicationContext(getClass().getSimpleName() + "-regionProvider.xml",AmazonSimpleEmailServiceClient.class); MailSender mailSender = context.getBean(MailSender.class); //Assert assertEquals("https://email.ap-southeast-2.amazonaws.com",getEndpointUrlFromWebserviceClient(emailService)); assertTrue(mailSender instanceof JavaMailSender); }
@Test public void parse_MailSenderWithCustomSesClient_createMailSenderWithCustomSesClient() throws Exception { //Arrange ClasspathXmlApplicationContext context = new ClasspathXmlApplicationContext(getClass().getSimpleName() + "-ses-client.xml",getClass()); //Act AmazonSimpleEmailServiceClient emailService = context.getBean("emailServiceClient",AmazonSimpleEmailServiceClient.class); MailSender mailSender = context.getBean(MailSender.class); //Assert assertSame(emailService,ReflectionTestUtils.getField(mailSender,"emailService")); }
@Test public void sendSimpleMessage() throws Exception { AmazonSimpleEmailServiceClient sesClient = provider.getClient(); Assume.assumeNotNull("AWS client not null",sesClient); WildFlyCamelContext camelctx = new WildFlyCamelContext(); camelctx.getNamingContext().bind("sesClient",sesClient); camelctx.addRoutes(new RouteBuilder() { public void configure() { from("direct:start") .to("aws-ses://" + SESUtils.FROM + "?amazonSESClient=#sesClient"); } }); camelctx.start(); try { Exchange exchange = ExchangeBuilder.anExchange(camelctx) .withHeader(SesConstants.SUBJECT,SESUtils.SUBJECT) .withHeader(SesConstants.TO,Collections.singletonList(SESUtils.TO)) .withBody("Hello World!") .build(); ProducerTemplate producer = camelctx.createProducerTemplate(); Exchange result = producer.send("direct:start",exchange); String messageId = result.getIn().getHeader(SesConstants.MESSAGE_ID,String.class); Assert.assertNotNull("MessageId not null",messageId); } finally { camelctx.stop(); } }
public static AmazonSimpleEmailServiceClient createEmailClient() { BasicCredentialsProvider credentials = BasicCredentialsProvider.standard(); AmazonSimpleEmailServiceClient client = !credentials.isValid() ? null : (AmazonSimpleEmailServiceClient) AmazonSimpleEmailServiceClientBuilder.standard() .withCredentials(credentials) .withRegion("eu-west-1") .build(); return client; }
public AmazonSimpleEmailService createClient() { return AmazonSimpleEmailServiceClient .builder() .withRegion(Regions.US_EAST_1) .build(); }
@Override public void send(List<String> to,boolean htmlContent,Set<Attachment> attachments) { if (CollectionUtils.isEmpty(to)) { throw new IllegalArgumentException("to must be defined."); } if (isBlank(content)) { throw new IllegalArgumentException("content must be defined."); } if (attachments == null) { sendSimpleMail(to,cc,ci,object,content,htmlContent); } else { Session session = Session.getDefaultInstance(new Properties()); MimeMessage message = new MimeMessage(session); try { message.setSubject(object); message.setFrom(new InternetAddress(from)); addRecipients(message,javax.mail.Message.RecipientType.TO,to); addRecipients(message,javax.mail.Message.RecipientType.CC,cc); addRecipients(message,javax.mail.Message.RecipientType.BCC,ci); MimeBodyPart wrap = new MimeBodyPart(); MimeMultipart cover = new MimeMultipart("alternative"); MimeBodyPart html = new MimeBodyPart(); cover.addBodyPart(html); wrap.setContent(cover); MimeMultipart multiPartContent = new MimeMultipart("related"); message.setContent(multiPartContent); multiPartContent.addBodyPart(wrap); for (Attachment attachment : attachments) { MimeBodyPart attachmentPart = new MimeBodyPart(); attachmentPart.setHeader("Content-ID","<" + attachment.getId() + ">"); attachmentPart.setFileName(attachment.getFileName()); attachmentPart.setContent(attachment.getContent(),attachment.mineType()); multiPartContent.addBodyPart(attachmentPart); } html.setContent(content,mine_TEXT_HTML); // Send the email. ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); message.writeto(outputStream); RawMessage rawMessage = new RawMessage(ByteBuffer.wrap(outputStream.toByteArray())); SendRawEmailRequest rawEmailRequest = new SendRawEmailRequest(rawMessage); AmazonSimpleEmailServiceClient client = new AmazonSimpleEmailServiceClient(); client.setRegion(region); client.sendRawEmail(rawEmailRequest); } catch (MessagingException | IOException e) { e.printstacktrace(); } } }
public AmazonSimpleEmailServiceClient ses() { validateCredentials(); return sesClient; }
@Bean @ConditionalOnMissingAmazonClient(AmazonSimpleEmailService.class) public AmazonWebserviceClientfactorybean<AmazonSimpleEmailServiceClient> amazonSimpleEmailService(AWSCredentialsProvider credentialsProvider) { return new AmazonWebserviceClientfactorybean<>(AmazonSimpleEmailServiceClient.class,credentialsProvider,this.regionProvider); }
private static String getEndpointUrlFromWebserviceClient(AmazonSimpleEmailServiceClient client) throws Exception { Field field = findField(AmazonSimpleEmailServiceClient.class,"endpoint"); makeAccessible(field); URI endpointUri = (URI) field.get(client); return endpointUri.toASCIIString(); }
SESClientProvider(AmazonSimpleEmailServiceClient client) { this.client = client; }
public AmazonSimpleEmailServiceClient getClient() { return client; }
@Produces @Singleton public SESClientProvider getClientProvider() throws Exception { AmazonSimpleEmailServiceClient client = SESUtils.createEmailClient(); return new SESClientProvider(client); }
com.amazonaws.services.simpleemail.AmazonSimpleEmailService的实例源码
@Test public void testSendSimpleMailWithMinimalProperties() throws Exception { AmazonSimpleEmailService emailService = mock(AmazonSimpleEmailService.class); SimpleEmailServiceMailSender mailSender = new SimpleEmailServiceMailSender(emailService); SimpleMailMessage simpleMailMessage = createSimpleMailMessage(); ArgumentCaptor<SendEmailRequest> request = ArgumentCaptor.forClass(SendEmailRequest.class); when(emailService.sendEmail(request.capture())).thenReturn(new SendEmailResult().withMessageId("123")); mailSender.send(simpleMailMessage); SendEmailRequest sendEmailRequest = request.getValue(); assertEquals(simpleMailMessage.getFrom(),sendEmailRequest.getSource()); assertEquals(simpleMailMessage.getTo()[0],sendEmailRequest.getDestination().getToAddresses().get(0)); assertEquals(simpleMailMessage.getSubject(),sendEmailRequest.getMessage().getSubject().getData()); assertEquals(simpleMailMessage.getText(),sendEmailRequest.getMessage().getBody().getText().getData()); assertEquals(0,sendEmailRequest.getDestination().getCcAddresses().size()); assertEquals(0,sendEmailRequest.getDestination().getBccAddresses().size()); }
@Test public void testCreateMimeMessageWithExceptionInInputStream() throws Exception { InputStream inputStream = mock(InputStream.class); AmazonSimpleEmailService emailService = mock(AmazonSimpleEmailService.class); JavaMailSender mailSender = new SimpleEmailServiceJavaMailSender(emailService); IOException ioException = new IOException("error"); when(inputStream.read(ArgumentMatchers.any(byte[].class),ArgumentMatchers.anyInt(),ArgumentMatchers.anyInt())).thenThrow(ioException); try { mailSender.createMimeMessage(inputStream); fail("MailPreparationException expected due to error while creating mail"); } catch (MailParseException e) { assertTrue(e.getMessage().startsWith("Could not parse raw MIME content")); assertSame(ioException,e.getCause().getCause()); } }
@Test public void testSendMultipleMailsWithException() throws Exception { AmazonSimpleEmailService emailService = mock(AmazonSimpleEmailService.class); JavaMailSender mailSender = new SimpleEmailServiceJavaMailSender(emailService); MimeMessage failureMail = createMimeMessage(); when(emailService.sendRawEmail(ArgumentMatchers.isA(SendRawEmailRequest.class))). thenReturn(new SendRawEmailResult()). thenThrow(new AmazonClientException("error")). thenReturn(new SendRawEmailResult()); try { mailSender.send(createMimeMessage(),failureMail,createMimeMessage()); fail("Exception expected due to error while sending mail"); } catch (MailSendException e) { assertEquals(1,e.getFailedMessages().size()); assertTrue(e.getFailedMessages().containsKey(failureMail)); } }
@Test public void send() throws IOException,TemplateException { Mailer mailer = mock(Mailer.class); mailer.setTemplateConfiguration(LinkGeneratorLambdaHandler.templateConfiguration); doReturn("Content").when(mailer).createBody(); doCallRealMethod().when(mailer).send(); AmazonSimpleEmailService client = mock(AmazonSimpleEmailService.class); doReturn(mock(SendEmailResult.class)).when(client).sendEmail(any()); doReturn(client).when(mailer).createClient(); mailer.send(); verify(client,times(1)).sendEmail(any()); }
@Test public void createClient() throws IOException,TemplateException { Mailer mailer = mock(Mailer.class); doCallRealMethod().when(mailer).createClient(); Object client = mailer.createClient(); assertthat(client,instanceOf(AmazonSimpleEmailService.class)); }
@Override void makeSend(String to,String subject,String msg) { String accessKey = config.readString(ConfigProperty.SES_ACCESS_KEY); String secretKey = config.readString(ConfigProperty.SES_SECRET_KEY); if (!Strings.isNullOrEmpty(accessKey)) { Destination destination = new Destination().withToAddresses(to); Content subj = new Content().withData(subject); Content textBody = new Content().withData(msg); Body body = new Body().withHtml(textBody); Message message = new Message().withSubject(subj).withBody(body); SendEmailRequest req = new SendEmailRequest().withSource(config.readString(ConfigProperty.EMAIL_DEFAULT_FROM_NAME) + " <" + config.readString(ConfigProperty.EMAIL_DEFAULT_FROM) + ">") .withDestination(destination).withMessage(message); AmazonSimpleEmailService client = AmazonSimpleEmailServiceClientBuilder.standard() .withRegion(config.readString(ConfigProperty.SES_REGION)) .withCredentials(new AWsstaticCredentialsProvider(new BasicAWSCredentials(accessKey,secretKey))) .build(); try { client.sendEmail(req); } finally { client.shutdown(); } } else { throw new IllegalStateException("SES Mail provider wasn't configured well."); } }
@Test public void testSendMultipleMails() throws Exception { AmazonSimpleEmailService emailService = mock(AmazonSimpleEmailService.class); SimpleEmailServiceMailSender mailSender = new SimpleEmailServiceMailSender(emailService); ArgumentCaptor<SendEmailRequest> request = ArgumentCaptor.forClass(SendEmailRequest.class); when(emailService.sendEmail(request.capture())).thenReturn(new SendEmailResult().withMessageId("123")); mailSender.send(createSimpleMailMessage(),createSimpleMailMessage()); verify(emailService,times(2)).sendEmail(ArgumentMatchers.any(SendEmailRequest.class)); }
@Test public void testShutDownOfResources() throws Exception { AmazonSimpleEmailService emailService = mock(AmazonSimpleEmailService.class); SimpleEmailServiceMailSender mailSender = new SimpleEmailServiceMailSender(emailService); mailSender.destroy(); verify(emailService,times(1)).shutdown(); }
@Test public void testSendMimeMessage() throws MessagingException,IOException { AmazonSimpleEmailService emailService = mock(AmazonSimpleEmailService.class); JavaMailSender mailSender = new SimpleEmailServiceJavaMailSender(emailService); ArgumentCaptor<SendRawEmailRequest> request = ArgumentCaptor.forClass(SendRawEmailRequest.class); when(emailService.sendRawEmail(request.capture())).thenReturn(new SendRawEmailResult().withMessageId("123")); MimeMessage mimeMessage = createMimeMessage(); mailSender.send(mimeMessage); SendRawEmailRequest rawEmailRequest = request.getValue(); assertTrue(Arrays.equals(getMimeMessageAsByteArray(mimeMessage),rawEmailRequest.getRawMessage().getData().array())); }
@Test public void testSendMultipleMimeMessages() throws Exception { AmazonSimpleEmailService emailService = mock(AmazonSimpleEmailService.class); JavaMailSender mailSender = new SimpleEmailServiceJavaMailSender(emailService); when(emailService.sendRawEmail(ArgumentMatchers.isA(SendRawEmailRequest.class))).thenReturn(new SendRawEmailResult().withMessageId("123")); mailSender.send(createMimeMessage(),createMimeMessage()); verify(emailService,times(2)).sendRawEmail(ArgumentMatchers.isA(SendRawEmailRequest.class)); }
@Override public Parameters handleRequest(Parameters parameters,Context context) { context.getLogger().log("Input Function [" + context.getFunctionName() + "],Parameters [" + parameters + "]"); try { // Create an empty Mime message and start populating it Session session = Session.getDefaultInstance(new Properties()); MimeMessage message = new MimeMessage(session); message.setSubject(EMAIL_SUBJECT,"UTF-8"); message.setFrom(new InternetAddress(System.getenv("EMAIL_FROM"))); message.setReplyTo(new Address[] { new InternetAddress(System.getenv("EMAIL_FROM")) }); message.setRecipients(Message.RecipientType.TO,InternetAddress.parse(System.getenv("EMAIL_RECIPIENT"))); MimeBodyPart wrap = new MimeBodyPart(); MimeMultipart cover = new MimeMultipart("alternative"); MimeBodyPart html = new MimeBodyPart(); cover.addBodyPart(html); wrap.setContent(cover); MimeMultipart content = new MimeMultipart("related"); message.setContent(content); content.addBodyPart(wrap); // Create an S3 URL reference to the snapshot that will be attached to this email URL attachmentURL = createSignedURL(parameters.getS3Bucket(),parameters.getS3Key()); StringBuilder sb = new StringBuilder(); String id = UUID.randomUUID().toString(); sb.append("<img src=\"cid:"); sb.append(id); sb.append("\" alt=\"ATTACHMENT\"/>\n"); // Add the attachment as a part of the message body MimeBodyPart attachment = new MimeBodyPart(); DataSource fds = new URLDataSource(attachmentURL); attachment.setDataHandler(new DataHandler(fds)); attachment.setContentID("<" + id + ">"); attachment.setdisposition(BodyPart.ATTACHMENT); attachment.setFileName(fds.getName()); content.addBodyPart(attachment); // Pretty print the Rekognition Labels as part of the Emails HTML content String prettyPrintLabels = parameters.getRekognitionLabels().toString(); prettyPrintLabels = prettyPrintLabels.replace("{","").replace("}",""); prettyPrintLabels = prettyPrintLabels.replace(",","<br>"); html.setContent("<html><body><h2>Uploaded Filename : " + parameters.getS3Key().replace("upload/","") + "</h2><p><b>Detected Labels/Confidence</b><br><br>" + prettyPrintLabels + "</p>"+sb+"</body></html>","text/html"); // Convert the JavaMail message into a raw email request for sending via SES ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); message.writeto(outputStream); RawMessage rawMessage = new RawMessage(ByteBuffer.wrap(outputStream.toByteArray())); SendRawEmailRequest rawEmailRequest = new SendRawEmailRequest(rawMessage); // Send the email using the AWS SES Service AmazonSimpleEmailService client = AmazonSimpleEmailServiceClientBuilder.defaultClient(); client.sendRawEmail(rawEmailRequest); } catch (MessagingException | IOException e) { // Convert Checked Exceptions to RuntimeExceptions to ensure that // they get picked up by the Step Function infrastructure throw new AmazonServiceException("Error in ["+context.getFunctionName()+"]",e); } context.getLogger().log("Output Function [" + context.getFunctionName() + "],Parameters [" + parameters + "]"); return parameters; }
public AmazonSimpleEmailService createClient() { return AmazonSimpleEmailServiceClient .builder() .withRegion(Regions.US_EAST_1) .build(); }
public AmazonMailDeliveryServiceImpl(final AmazonSimpleEmailService amazonSimpleEmailService) { this.amazonSimpleEmailService = amazonSimpleEmailService; }
public AmazonSimpleEmailService getAmazonSESClient() { return amazonSESClient; }
/** * To use the AmazonSimpleEmailService as the client */ public void setAmazonSESClient(AmazonSimpleEmailService amazonSESClient) { this.amazonSESClient = amazonSESClient; }
public AmazonSimpleEmailService getSESClient() { return sesClient; }
@Bean @ConditionalOnMissingAmazonClient(AmazonSimpleEmailService.class) public AmazonWebserviceClientfactorybean<AmazonSimpleEmailServiceClient> amazonSimpleEmailService(AWSCredentialsProvider credentialsProvider) { return new AmazonWebserviceClientfactorybean<>(AmazonSimpleEmailServiceClient.class,credentialsProvider,this.regionProvider); }
@Bean @ConditionalOnMissingClass("org.springframework.cloud.aws.mail.simplemail.SimpleEmailServiceJavaMailSender") public MailSender simpleMailSender(AmazonSimpleEmailService amazonSimpleEmailService) { return new SimpleEmailServiceMailSender(amazonSimpleEmailService); }
@Bean @ConditionalOnClass(name = "javax.mail.Session") public JavaMailSender javaMailSender(AmazonSimpleEmailService amazonSimpleEmailService) { return new SimpleEmailServiceJavaMailSender(amazonSimpleEmailService); }
public SimpleEmailServiceMailSender(AmazonSimpleEmailService amazonSimpleEmailService) { this.emailService = amazonSimpleEmailService; }
protected AmazonSimpleEmailService getEmailService() { return this.emailService; }
public SimpleEmailServiceJavaMailSender(AmazonSimpleEmailService amazonSimpleEmailService) { super(amazonSimpleEmailService); }
JavaMailSenderImpl
Spring提供了简化发送邮件类JavaMailSenderImpl.结合spring可以像下面实现灵活配置。
<bean id="mailSender">
<property name="username" value="XXX@gmail.com" />
<property name="password" value="XXX" />
<property name="javaMailProperties">
<props>
<prop key="mail.smtp.from">XXX@gmail.com</prop>
<prop key="mail.smtp.user">XXX@gmail.com</prop>
<prop key="mail.smtp.password">XXX</prop>
<prop key="mail.smtp.host">smtp.gmail.com</prop>
<prop key="mail.smtp.port">587</prop>
<prop key="mail.smtp.auth">true</prop>
<prop key="mail.smtp.starttls.enable">true</prop>
</props>
</property>
</bean>
接下来尝试着发送 一些简单的文本到发送丰富的velocity.今天的关于如何强制JavaMailSenderImpl使用TLS1.2?和java强行的分享已经结束,谢谢您的关注,如果想了解更多关于com.amazonaws.services.simpleemail.AmazonSimpleEmailServiceClientBuilder的实例源码、com.amazonaws.services.simpleemail.AmazonSimpleEmailServiceClient的实例源码、com.amazonaws.services.simpleemail.AmazonSimpleEmailService的实例源码、JavaMailSenderImpl的相关知识,请在本站进行查询。
本文标签: