Create an account


Welcome, Guest
You have to register before you can post on our site.

Username
  

Password
  





Search Forums

(Advanced Search)

Forum Statistics
» Members: 20,134
» Latest member: jax9090nnn
» Forum threads: 21,936
» Forum posts: 22,806

Full Statistics

Online Users
There are currently 3446 online users.
» 0 Member(s) | 3441 Guest(s)
Applebot, Baidu, Bing, Google, Yandex

 
  (Free Game Key) Master of Magic Classic - Free GOG Game
Posted by: xSicKxBot - 09-30-2022, 11:19 AM - Forum: Deals or Specials - No Replies

Master of Magic Classic - Free GOG Game

This giveaway is on gog.com gog is a platform for games that is dedicated to drm-free games (those are games that do not require login or registration to play the game)

How to grab Master of Magic Classic
- Go to the home page of https://gog.com
- Login and Register
- Go to the home page again
- Wait for 10 seconds then start searching for Master of Magic Classic
- on the home page look for "Deal of the Day" (above it there should be a banner)
- on the banner there is a button "Yes, and claim the game" click it
- Thats it


GOG Store link: https://www.gog.com/en/game/master_of_magic_classic
Auto-claim link: https://www.gog.com/giveaway/claim
This game is free to claim for less than 48 hours until Sunday, October 2, 2022 4:00 PM

We are welcoming everyone to join our discord[discord.gg]. We are more active there on finding giveaways, small or large, and there are daily raffles you can participate.

?GrabFreeGames.com ?Twitter ?Steam Curator ?Facebook[fb.me]?Discord[discord.gg]
❤️Support us: HumbleBundle Partner[www.humblebundle.com] Fanatical Affiliate[www.fanatical.com]


https://steamcommunity.com/groups/GrabFr...9931429072

Print this item

  PC - Blind Fate: Edo no Yami
Posted by: xSicKxBot - 09-30-2022, 11:19 AM - Forum: New Game Releases - No Replies

Blind Fate: Edo no Yami



It's a new, dark and machine-filled Edo period, and the Shogunate rules over Japan with its just, but pitiless hand: you.

You follow orders. You obey. You kill.

Until your sight is taken from you, and you must learn to "feel" the world anew...

Dive into a world that mixes Sci-Fi and ancient tradition. Slash through robots with a trusty katana, use hi-tech implants to navigate the surroundings, dodge enemy attacks, and land devastating finishers. Reclaim the past following the way of the Japanese samurai in the fantastic period of New Edo.

Publisher: 101XP

Release Date: Sep 15, 2022




https://www.metacritic.com/game/pc/blind...do-no-yami

Print this item

  [Oracle Blog] JavaOne Update Series: Run of Show
Posted by: xSicKxBot - 09-29-2022, 05:12 AM - Forum: Java Language, JVM, and the JRE - No Replies

JavaOne Update Series: Run of Show

JavaOne is nearly upon us and we’ve been working hard to fill out the list of final activities. Here’s a high-level Run of Show to give you a sense for what you can expect from the first JavaOne in 5 years. Note that the JavaOne conference is co-located with CloudWorld, so I will mix in a few notable things like the CloudWorld keynotes and the Steve Miller Band. Rock on!

https://blogs.oracle.com/java/post/javao...un-of-show

Print this item

  [Tut] How to Stop a For Loop in Python
Posted by: xSicKxBot - 09-29-2022, 05:12 AM - Forum: Python - No Replies

How to Stop a For Loop in Python

Rate this post

Python provides three ways to stop a for loop:

  1. The for loop ends naturally when all elements have been iterated over. After that, Python proceeds with the first statement after the loop construct.
  2. The keyword break terminates a loop immediately. The program proceeds with the first statement after the loop construct.
  3. The keyword continue terminates only the current loop iteration, but not the whole loop. The program proceeds with the first statement in the loop body.

You can see each of these three methods to terminate a for loop in the following graphic:

How to Stop a For Loop in Python

Let’s dive into each of those three approaches next!

Method 1: Visit All Elements in Iterator


The most natural way to end a Python for loop is to deplete the iterator defined in the loop expression for <var> in <iterator>. If the iterator’s next() method doesn’t return a value anymore, the program proceeds with the next statement after the loop construct. This immediately ends the loop.

Here’s an example that shows how the for loop ends as soon as all elements have been visited in the iterator returned by the range() function:

s = 'hello world' for c in range(5): print(c, end='') # hello

? Recommended Tutorial: Iterators, Iterables, and Itertools

Method 2: Keyword “break”


If the program executes a statement with the keyword break, the loop terminates immediately. No other statement in the loop body is executed and the program proceeds with the first statement after the loop construct. In most cases, you’d use the keyword break in an if construct to decide dynamically whether a loop should end, or not.

In the following example, we create a string with 11 characters and enter a for loop that ends prematurely after five iterations — using the keyword break in an if condition to accomplish that:

s = 'hello world' for i in range(10): print(s[i], end='') if i == 5: break # hello

As soon as the if condition evaluates to False, the break statement is executed—the loop ends.

? Recommended Tutorial: How to End a While Loop?

Method 3: Keyword “continue”


The keyword continue terminates only the current loop iteration, but not the whole loop. The program proceeds with the first statement in the loop body. The most common use of continue is to avoid the execution of certain parts of the loop body, constrained by a condition checked in an if construct.

Here’s an example:

for i in range(10): if i == 5: break else: continue print('NEVER EXECUTED')

Python iterates over an iterator with 10 elements. However, in each iteration, it either ends the loop using break or continues with the next iteration using continue.

However, the remaining loop body that actually does something such as printing 'NEVER EXECUTED' is, well, never executed.

Python Keywords Cheat Sheet


You can learn about the most important Python keywords in this concise cheat sheet—if you’re like me, you love cheat sheets as well! ⤵

Python Cheat Sheet Keywords

You can download it here:

Summary


You’ve learned three ways to terminate a while loop.

  • Method 1: The for loop terminates automatically after all elements have been visited. You can modify the iterator using the __next__() dunder method.
  • Method 2: The keyword break terminates a loop immediately. The program proceeds with the first statement after the loop construct.
  • Method 3: The keyword continue terminates only the current loop iteration, but not the whole loop. The program proceeds with the first statement in the loop body.

Thanks for reading this tutorial—if you want to boost your Python skills further, I’d recommend you check out my free email academy and download the free Python lessons and cheat sheets here:

Join us, it’s fun! ?

Programmer Humor


❓ Question: How did the programmer die in the shower? ☠

Answer: They read the shampoo bottle instructions:
Lather. Rinse. Repeat.



https://www.sickgaming.net/blog/2022/09/...in-python/

Print this item

  [Tut] Datatrans Payments API for Secure Payment
Posted by: xSicKxBot - 09-29-2022, 05:12 AM - Forum: PHP Development - No Replies

Datatrans Payments API for Secure Payment

by Vincy. Last modified on September 28th, 2022.

Datatrans is one of the popular payment gateway systems in Europe for e-commerce websites. It provides frictionless payment solutions.

The Datatrans Payment gateway is widely popular in European countries. One of my clients from Germany required this payment gateway integrated into their online shop.

In this tutorial, I share the knowledge of integrating Datatrans in a PHP application. It will save the developers time to do research with the long-form documentation.

There are many integration options provided by this payment gateway.

  1. Redirect and lightbox
  2. Secure fields
  3. Mobile SDK
  4. API endpoints

In this tutorial, we will see the first integration option to set up the Datatrans payment gateway. We have seen many payment gateway integration examples in PHP in the earlier articles.

A working example follows helps to understand things easily. Before seeing the example, get the Datatrans merchant id and password. It will be useful for authentication purposes while accessing this payment API.

datatrans api payment

Get Datatrans merchant id and password


The following steps lead to getting the merchant id and password of your Datatrans account.

    1. Open a Datatrans sandbox account and verify it via email.
    2. Set up your account by selecting the username, group name(Login) and password.
    3. After Set up it will show the following details
      • Login credentials.
      • Sandbox URL of the admin dashboard.
      • Datatrans Merchant Id for Web, Mobile SDK.
    4. Visit the sandbox URL and log in using the credential got in step 3.
    5. Click Change Merchant and Choose merchant to see the dashboard.
    6. Go to UPP Administration -> Security to copy the (Marchant Id)Username and Password for API access.

When we see CCAvenue payment integration, it also listed a few steps to get the merchant id from the dashboard.

datatrans merchant account credentials

Application configuration


This config file is created for this example to have the API keys used across the code.

It configures the URL that has to be called by the DataTrans server after the payment.

Config.php (Configure Datatrans authentication details)

<?php
class Config { const WEB_ROOT = 'http://localhost/pp-article-code/data-trans/'; const MERCHANT_ID = 'YOUR_MERCHANT_ID'; const PASSWORD = 'YOUR_MERCHANT_DASHBOARD_PASSWORD'; const SUCCESS_URL = Config::WEB_ROOT . 'return.php'; const CANCEL_URL = Config::WEB_ROOT . 'return.php?status=cancelled'; const ERROR_URL = Config::WEB_ROOT . 'return.php?status=error';
}
?>

Show the “Pay now” option


First, a landing page shows a product tile with a payment option. It will show a “Pay via DataTrans” button in the browser.

On clicking this button, it will call the AJAX script to get the transaction id.

This page includes the Datatrans JavaScript library to start payment with the transaction id.

index.php (Product tile with pay button)

<HTML>
<HEAD>
<TITLE>Datatrans Payments API for Secure Payment</TITLE>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script> </HEAD>
<BODY> <div class="container"> <h1>Datatrans Payments API for Secure Payment</h1> <div class="outer-container"> <img src="image/camera.jpg" alt="camera image"> <div class="inner-container"> <p class="text-style">A6900 MirrorLess Camera</p> <p class="price-color-align"> $289.61<input type="hidden" name="amount" id="amount" value="289.61" /> </p> <input type="button" id="pay-now" class="pay-button" value="Pay via DataTrans" on‌Click="initiate()" /> </div> </div> </div> <script src="https://pay.sandbox.datatrans.com/upp/payment/js/datatrans-2.0.0.js"></script>
</BODY>
</HTML>

Get transaction id and proceed with payment via API


The initiate() function posts the amount to the PHP file to initiate Datatrans payment.

As the result, the PHP will return the transaction id to process the payment further.

The proceedPayment() function calls the Datatrans JavaScript API to start the payment. It will show a Datatrans overlay with card options to choose payment methods.

index.php (AJAX script to call Datatrans initiation)

function initiate() { $.ajax({ method: "POST", url: "initialize-datatrans-ajax.php", dataType: "JSON", data: { "amount": $("#amount").val() } }) .done(function(response) { if (response.responseType == 'success') { proceedPayment(response.transactionId); } else { alert(response.responseType + ": " + response.message); } }); }; function proceedPayment(transactionId) { Datatrans.startPayment({ transactionId: transactionId, 'opened': function() { console.log('payment-form opened'); }, 'loaded': function() { console.log('payment-form loaded'); }, 'closed': function() { console.log('payment-page closed'); }, 'error': function() { console.log('error'); } });
}

Initiate payment transaction to get the Datatrans payment transaction id


This file is the PHP endpoint called via AJAX script to get the Datatrans transaction id.

It invokes the DatatransPaymentService to post the cURL request to the Datatrans API. It requested to initiate the payment and receives the transaction id from the Datatrans server.

This output will be read in the AJAX success callback to start the payment via the JavaScript library.

initialize-datatrans-ajax.php

<?php
require_once 'DatatransPaymentService.php';
$dataTransPaymentService = new DatatransPaymentService();
$amount = $_POST["amount"];
$orderId = rand();
$result = $dataTransPaymentService->initializeTransaction($amount, $orderId);
print $result;
?>

Datatrans payment transaction service to call API via PHP cURL


This service call contains the initializeTransaction() method which prepares the cURL request in PHP to the Datatrans API.

It passed the amount, currency and more details to the API endpoint to request the transaction id.

DatatransPaymentService.php

<?php class DatatransPaymentService
{ public function initializeTransaction($amount, $orderId) { $url = 'https://api.sandbox.datatrans.com/v1/transactions'; require_once __DIR__ . '/Config.php'; $amount = $amount * 100; $postFields = json_encode(array( 'amount' => $amount, 'currency' => "USD", 'refno' => $orderId, 'redirect' => [ 'successUrl' => Config::SUCCESS_URL, "cancelUrl" => Config::CANCEL_URL, "errorUrl" => Config::ERROR_URL ] )); $key = Config::MERCHANT_ID . ':' . Config::PASSWORD; $keyBase64 = base64_encode($key); $ch = curl_init(); curl_setopt_array($ch, array( CURLOPT_URL => $url, CURLOPT_RETURNTRANSFER => true, CURLOPT_CUSTOMREQUEST => "POST", CURLOPT_POSTFIELDS => $postFields, CURLOPT_HTTPAUTH => CURLAUTH_BASIC, CURLOPT_HTTPHEADER => array( "Authorization: Basic " . $keyBase64, "Content-Type: application/json" ) )); $curlResponse = curl_exec($ch); $curlJSONObject = json_decode($curlResponse); if (empty($curlResponse)) { $curlError = curl_error($ch); } else if (! empty($curlJSONObject->error)) { $curlError = $curlJSONObject->error->code . ": " . $curlJSONObject->error->message; } curl_close($ch); if (empty($curlJSONObject->transactionId)) { $result = array( 'responseType' => "Error", 'message' => $curlError ); } else { $result = array( 'responseType' => "success", 'transactionId' => $curlJSONObject->transactionId ); } $result = json_encode($result); return $result; }
}
?>

Call application URL after payment


return.php

<HTML>
<HEAD>
<TITLE>Datatrans payment status notice</TITLE>
</HEAD>
<BODY> <div class="text-center">
<?php
if (! empty($_GET["status"])) { ?> <h1>Something wrong with the payment process!</h1> <p>Kindly contact admin with the reference of your transaction id <?php echo $_GET["datatransTrxId"]; ?></p>
<?php
} else { ?> <h1>Your order has been placed</h1> <p>We will contact you shortly.</p>
<?php
}
?>
</div>
</BODY>
</HTML>

Download

↑ Back to Top



https://www.sickgaming.net/blog/2022/09/...e-payment/

Print this item

  (Indie Deal) FREE Larry 7, Jazzy Beats 2 Bundle & a JoJo reference?
Posted by: xSicKxBot - 09-29-2022, 05:12 AM - Forum: Deals or Specials - No Replies

FREE Larry 7, Jazzy Beats 2 Bundle & a JoJo reference?

Leisure Suit Larry 7 - Love for Sail FREEbie
[freebies.indiegala.com]
Don't miss the final classic installment of the hottest point-and-click adventure in existence!

JoJo's Bizarre Adventure: All-Star Battle R out now
[www.indiegala.com]
https://www.youtube.com/watch?v=CsAx6uYdpRc
Jazzy Beats #2 Bundle | 12 Music Albums | 93% OFF
[www.indiegala.com]
Check out our new Jazz Hop Café bundle full of relaxing tracks to vibe/study to, tunes brought by Prithvi, HoKø, Refeeld, Kissamilé, Rakuyou, Rakuyou, Stuffed Tomato, S N U G & WYS. Accept lofi into your life, start an audio romance and go on a journey of discovery.

Intragames Sale, UP TO 80% OFF
[www.indiegala.com]
Cashback bonus also applies.

https://www.youtube.com/watch?v=Kq7hYzcQ_EU


https://steamcommunity.com/groups/indieg...4557853406

Print this item

  News - Steam Autumn Sale Runs During Black Friday, Full 2022 Schedule Revealed
Posted by: xSicKxBot - 09-29-2022, 05:12 AM - Forum: Lounge - No Replies

Steam Autumn Sale Runs During Black Friday, Full 2022 Schedule Revealed

We're entering the holiday season, which means a bunch of gaming sales are coming up. For many PC gamers, the biggest promotions each year happen over on Steam. The sales always offer great opportunities to stock up on PC games for cheap. We still have two major Steam sales on the horizon before the end of 2022, and Valve has announced dates for both of them as well as changes to the schedule in 2023.

Steam sale schedule

  • Autumn Sale - November 22-29
  • Winter Sale - December 22-January 5
  • Spring Sale - March 16-23, 2023

Steam's Autumn Sale will run November 22-29. As usual, this sale lines up with Thanksgiving (and Black Friday) week, so you'll have plenty to shop at Steam and other major retailers. The timing is perfect considering PC gaming components, laptops, and peripherals see major discounts during Black Friday. After grabbing the PC gear that you want, you'll be able to pick up a bunch of games for cheap to play with your new gear.

Continue Reading at GameSpot

https://www.gamespot.com/articles/steam-...01-10abi2f

Print this item

  PC - Foretales
Posted by: xSicKxBot - 09-29-2022, 05:12 AM - Forum: New Game Releases - No Replies

Foretales



A terrible curse is ravaging the realm and the only one who can stop it is a small-time thief named Volepain.

The Weaver put in the hands of her children the fate of the world's creation and stability. The instruments of creation have the power to create and destroy the many worlds of Foretales.

Discover the true goals of the Nymphants and the Cult or embrace the Maelstorm for eternity!

Decide the fate of the world in this ingenious story-driven card game. Foretales offers a unique take on the adventure genre, with a multitude of playstyles and story paths through which you can save the world... or bring about its end.

Publisher: Dear Villagers

Release Date: Sep 15, 2022




https://www.metacritic.com/game/pc/foretales

Print this item

  [Tut] Send, Receive, and Test Emails in Django
Posted by: xSicKxBot - 09-28-2022, 12:28 PM - Forum: Python - No Replies

Send, Receive, and Test Emails in Django

5/5 – (1 vote)

Some time ago, we discovered how to send an email with Python using smtplib, a built-in email module. Back then, the focus was made on the delivery of different types of messages via SMTP server. Today, we prepared a similar tutorial but for Django.

This popular Python web framework allows you to accelerate email delivery and make it much easier. And these code samples of sending emails with Django are going to prove that.

A simple code example of how to send an email


Let’s start our tutorial with a few lines of code that show you how simple it is to send an email in Django.  Import send_mail in the beginning of the file:

from django.core.mail import send_mail

And call the code below in the necessary place.

send_mail( 'That’s your subject', 'That’s your message body', 'from@yourdjangoapp.com', ['to@yourbestuser.com'], fail_silently=False,
)

These lines are enclosed in the django.core.mail module that is based on smtplib. The message delivery is carried out via SMTP host, and all the settings are set by default:

EMAIL_HOST: 'localhost'
EMAIL_PORT: 25
EMAIL_HOST_USER: (Empty string)
EMAIL_HOST_PASSWORD: (Empty string)
EMAIL_USE_TLS: False
EMAIL_USE_SSL: False

Note that the character set of emails sent with django.core.mail are automatically set to the value of your DEFAULT_CHARSET setting.

You can learn about the other default values here. Most likely you will need to adjust them. Therefore, let’s tweak the settings.py file..

Setting up


Before actually sending your email, you need to set up for it. So, let’s add some lines to the settings.py file of your Django app.

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.yourserver.com'
EMAIL_PORT = '<your-server-port>'
EMAIL_HOST_USER = 'your@djangoapp.com'
EMAIL_HOST_PASSWORD = 'your-email account-password'
EMAIL_USE_TLS = True
EMAIL_USE_SSL = False

EMAIL_HOST is different for each email provider you use. For example, if you have a Gmail account and use their SMTP server, you’ll have EMAIL_HOST = ‘smtp.gmail.com’.

Also, validate other values that are relevant to your email server. Eventually, you need to choose the way to encrypt the mail and protect your user account by setting the variable EMAIL_USE_TLS or EMAIL_USE_SSL.

If you have an email provider that explicitly tells you which option to use, then it’s clear. Otherwise, you may try different combinations using True and False operators. Note that only one of these options can be set to True.

EMAIL_BACKEND tells Django which custom or predefined email backend will work with.

EMAIL_HOST. You can set up this parameter as well. 

SMTP email backend 


In the example above, EMAIL_BACKEND is specified as django.core.mail.backends.smtp.EmailBackend. It is the default configuration that uses SMTP server for email delivery. Defined email settings will be passed as matching arguments to EmailBackend.

host: EMAIL_HOST
port: EMAIL_PORT
username: EMAIL_HOST_USER
password: EMAIL_HOST_PASSWORD
use_tls: EMAIL_USE_TLS
use_ssl: EMAIL_USE_SSL

Unspecified arguments default to None

As well as .smtp.EmailBackend, you can use:

  • django.core.mail.backends.console.EmailBackend– the console backend that composes the emails that will be sent to the standard output. Not intended for production use.
  • django.core.mail.backends.filebased.EmailBackend – the file backend that creates emails in the form of a new file per each new session opened on the backend. Not intended for production use.
  • django.core.mail.backends.locmem.EmailBackend– the in-memory backend that stores messages in the local memory cache of django.core.mail.outbox. Not intended for production use.
  • django.core.mail.backends.dummy.EmailBackend – the dummy cache backend that implements the cache interface and does nothing with your emails. Not intended for production use.
  • Any out-of-the-box backend for Amazon SES, Mailgun, SendGrid, and other services. 

How to send emails via SMTP 


Once you have that configured, all you need to do to send an email is to import the send_mail or send_mass_mailfunction from django.core.mail.  These functions differ in the connection they use for messages. send_mailuses a separate connection for each message. send_mass_mailopens a single connection to the mail server and is mostly intended to handle mass emailing. 

Sending email with send_mail


This is the most basic function for email delivery in Django. It comprises four obligatory parameters to be specified: subject, message, from_email, and recipient_list

In addition to them, you can adjust the following:

  • auth_user: If EMAIL_HOST_USER has not been specified, or you want to override it, this username will be used to authenticate to the SMTP server. 
  • auth_password: If EMAIL_HOST_PASSWORD  has not been specified, this password will be used to authenticate to the SMTP server.
  • connection: The optional email backend you can use without tweaking EMAIL_BACKEND.
  • html_message: Lets you send multipart emails.
  • fail_silently: A boolean that controls how the backend should handle errors. If True – exceptions will be silently ignored. If Falsesmtplib.SMTPException will be raised. 

For example, it may look like this:

from django.core.mail import send_mail
send_mail( subject = 'That’s your subject' message = 'That’s your message body' from_email = 'from@yourdjangoapp.com' recipient_list = ['to@yourbestuser.com',] auth_user = 'Login' auth_password = 'Password' fail_silently = False,
)

Other functions for email delivery include mail_admins and mail_managers. Both are shortcuts to send emails to the recipients predefined in ADMINS and MANAGERS settings respectively.

For them, you can specify such arguments as subject, message, fail_silently, connection, and html_message.

The from_email argument is defined by the SERVER_EMAIL setting.

What is EmailMessage for? 


If the email backend handles the email sending, the EmailMessage class answers for the message creation. You’ll need it when some advanced features like BCC or an attachment are desirable. That’s how an initialized EmailMessage may look:

from django.core.mail import EmailMessage
email = EmailMessage( subject = 'That’s your subject', body = 'That’s your message body', from_email = 'from@yourdjangoapp.com', to = ['to@yourbestuser.com'], bcc = ['bcc@anotherbestuser.com'], reply_to = ['whoever@itmaybe.com'],
)

In addition to the EmailMessage objects you can see in the example, there are also other optional parameters:

  • connection: defines an email backend instance for multiple messages. 
  • attachments: specifies the attachment for the message.
  • headers: specifies extra headers like Message-ID or CC for the message. 
  • cc: specifies email addresses used in the “CC” header.

The methods you can use with the EmailMessage class are the following:

  • send: get the message sent.
  • message: composes a MIME object (django.core.mail.SafeMIMEText or django.core.mail.SafeMIMEMultipart).
  • recipients: returns a list of the recipients specified in all the attributes including to, cc, and bcc. 
  • attach: creates and adds a file attachment. It can be called with a MIMEBase instance or a triple of arguments consisting of filename, content, and mime type.
  • attach_file: creates an attachment using a file from a filesystem. We’ll talk about adding attachments a bit later.

How to send multiple emails


To deliver a message via SMTP, you need to open a connection and close it afterwards. This approach is quite awkward when you need to send multiple transactional emails. Instead, it is better to create one connection and reuse it for all messages.

This can be done with the send_messages method that the email backend API has. Check out the following example:

from django.core import mail
connection = mail.get_connection()
connection.open()
email1 = mail.EmailMessage( 'That’s your subject', 'That’s your message body', 'from@yourdjangoapp.com', ['to@yourbestuser1.com'], connection=connection,
)
email1.send()
email2 = mail.EmailMessage( 'That’s your subject #2', 'That’s your message body #2', 'from@yourdjangoapp.com', ['to@yourbestuser2.com'],
)
email3 = mail.EmailMessage( 'That’s your subject #3', 'That’s your message body #3', 'from@yourdjangoapp.com', ['to@yourbestuser3.com'],
)
connection.send_messages([email2, email3])
connection.close()

What you can see here is that the connection was opened for email1, and send_messages uses it to send emails #2 and #3. After that, you close the connection manually. 

How to send multiple emails with send_mass_mail


send_mass_mail is another option to use only one connection for sending different messages. 

message1 = ('That’s your subject #1', 'That’s your message body #1', 'from@yourdjangoapp.com', ['to@yourbestuser1.com', 'to@yourbestuser2.com'])
message2 = ('That’s your subject #2', 'That’s your message body #2', 'from@yourdjangoapp.com', ['to@yourbestuser2.com'])
message3 = ('That’s your subject #3', 'That’s your message body #3', 'from@yourdjangoapp.com', ['to@yourbestuser3.com'])
send_mass_mail((message1, message2, message3), fail_silently=False)

Each email message contains a datatuple made of subject, message, from_email, and recipient_list. Optionally, you can add other arguments that are the same as for send_mail.

How to send an HTML email


All versions starting from 1.7 let you send an email with HTML content using send_mail like this:

from django.core.mail import send_mail
subject = 'That’s your subject'
html_message = render_to_string('mail_template.html', {'context': 'values'})
plain_message = strip_tags(html_message)
from_email = 'from@yourdjangoapp.com>'
to = 'to@yourbestuser.com'
mail.send_mail(subject, plain_message, from_email, [to], html_message=html_message)

Older versions users will have to mess about with EmailMessage and its subclass EmailMultiAlternatives. It lets you include different versions of the message body using the attach_alternative method. For example:

from django.core.mail import EmailMultiAlternatives
subject = 'That’s your subject'
from_email = 'from@yourdjangoapp.com>'
to = 'to@yourbestuser.com'
text_content = 'That’s your plain text.'
html_content = '<p>That’s <strong>the HTML part</strong></p>'
message = EmailMultiAlternatives(subject, text_content, from_email, [to])
message.attach_alternative(html_content, "text/html")
message.send()

How to send an email with attachments


In the EmailMessage section, we’ve already mentioned sending emails with attachments. This can be implemented using attach or attach_file methods.

The first one creates and adds a file attachment through three arguments – filename, content, and mime type.

The second method uses a file from a filesystem as an attachment. That’s how each method would look like in practice:

message.attach('Attachment.pdf', file_to_be_sent, 'file/pdf')

or

message.attach_file('/documents/Attachment.pdf')

Custom email backend


You’re not limited to the abovementioned email backend options and can tailor your own. For this, you can use standard backends as a reference. Let’s say, you need to create a custom email backend with the SMTP_SSL connection support required to interact with Amazon SES.

The default SMTP backend will be the reference. First, add a new email option to settings.py.

AWS_ACCESS_KEY_ID = 'your-aws-access-key-id'
AWS_SECRET_ACCESS_KEY = 'your-aws-secret-access-key'
AWS_REGION = 'your-aws-region'
EMAIL_BACKEND = 'your_project_name.email_backend.SesEmailBackend'

Make sure that you are allowed to send emails with Amazon SES using these AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY (or error message will tell you about it :D)

Then create a file your_project_name/email_backend.py with the following content:

import boto3
from django.core.mail.backends.smtp import EmailBackend
from django.conf import settings
class SesEmailBackend(EmailBackend): def __init__( self, fail_silently=False, **kwargs ): super().__init__(fail_silently=fail_silently) self.connection = boto3.client( 'ses', aws_access_key_id=settings.AWS_ACCESS_KEY_ID, aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY, region_name=settings.AWS_REGION, ) def send_messages(self, email_messages): for email_message in email_messages: self.connection.send_raw_email( Source=email_message.from_email, Destinations=email_message.recipients(), RawMessage={"Data": email_message.message().as_bytes(linesep="\r\n")} )

This is the minimum needed to send an email using SES. Surely you will need to add some error handling, input sanitization, retries etc. but this is out of our topic.

You might see that we have imported boto3 in the beginning of the file. Don’t forget to install it using a command

pip install boto3

It’s not necessary to reinvent the wheel every time you need a custom email backend. You can find already existing libraries, or just receive SMTP credentials in your Amazon console and use the default email backend. It’s just about figuring out the best option for you and your project.

Sending emails using SES from Amazon


So far, you can benefit from several services that allow you to send transactional emails at ease. If you can’t choose one, check out our blog post about Sendgrid vs. Mandrill vs. Mailgun. It will help a lot. At this point, Mailtrap has launched its own sending solution.

So, you could easily start sending transactional emails in Django using our guide. But today, we’ll discover how to make your Django app send emails via Amazon SES. It is one of the most popular services so far. Besides, you can take advantage of a ready-to-use Django email backend for this service – django-ses.

Set up the library


You need to execute pip install django-ses to install django-ses. Once it’s done, tweak your settings.py with the following line:

EMAIL_BACKEND = 'django_ses.SESBackend'

AWS credentials


Don’t forget to set up your AWS account to get the required credentials – AWS access keys that consist of access key ID and secret access key.

For this, add a user in Identity and Access Management (IAM) service.

Then, choose a user name and Programmatic access type. Attach AmazonSESFullAccess permission and create a user. Once you’ve done this, you should see AWS access keys. Update your settings.py:

AWS_ACCESS_KEY_ID = '********'
AWS_SECRET_ACCESS_KEY = '********'

Email sending


Now, you can send your emails using django.core.mail.send_mail:

from django.core.mail import send_mail
send_mail( 'That’s your subject', 'That’s your message body', 'from@yourdjangoapp.com', ['to@yourbestuser.com']
)

django-ses is not the only preset email backend you can leverage. At the end of this article, you’ll find more useful libraries to optimize email delivery of your Django app. But first, a step you should never send emails without.

Testing email sending in Django 


Once you’ve got everything prepared for sending email messages, it is necessary to do some initial testing of your mail server. In Python, this can be done with one command:

python -m smtpd -n -c DebuggingServer localhost:1025

This allows you to send emails to your local SMTP server. The DebuggingServer feature won’t actually send the email but will let you see the content of your message in the shell window. That’s an option you can use off-hand.

Django’s TestCase


TestCase is a solution to test a few aspects of your email delivery. It uses locmem.EmailBackend, which, as you remember, stores messages in the local memory cache – django.core.mail.outbox. So, this test runner does not actually send emails. Once you’ve selected this email backend

EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend'

you can use the following unit test sample to test your email sending capability.

from django.core import mail
from django.test import TestCase
class EmailTest(TestCase): def test_send_email(self): mail.send_mail( 'That’s your subject', 'That’s your message body', 'from@yourdjangoapp.com', ['to@yourbestuser.com'], fail_silently=False, ) self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].subject, 'That’s your subject') self.assertEqual(mail.outbox[0].body, 'That’s your message body')

This code will test not only your email sending but also the correctness of the email subject and message body.

Testing with Mailtrap


Mailtrap can be a rich solution for testing. First, it lets you test not only the SMTP server but also the email content and do other essential checks from the email testing checklist. Second, it is a rather easy-to-use tool.

All you need to do is to copy the SMTP credentials from your demo inbox and tweak your settings.py. Or you can just copy/paste these four lines from the Integrations section by choosing Django in the pop-up menu.

EMAIL_HOST = 'smtp.mailtrap.io'
EMAIL_HOST_USER = '********'
EMAIL_HOST_PASSWORD = '*******'
EMAIL_PORT = '2525'

After that, feel free to send your HTML/CSS email with an attachment to check how it goes.

from django.core.mail import send_mail
subject = 'That’s your subject'
html_message = render_to_string('mail_template.html', {'context': 'values'}) plain_message = strip_tags(html_message)
from_email = 'from@yourdjangoapp.com>'
to = 'to@yourbestuser.com'
mail.send_mail(subject, plain_message, from_email, [to], html_message=html_message)
message.attach('Attachment.pdf', file_to_be_sent, 'file/pdf')

If there is no message in the Mailtrap Demo inbox or there are some issues with HTML content, you need to polish your code.

Django email libraries to simplify your life


As a conclusion to this blog post about sending emails with Django, we’ve included a brief introduction of a few libraries that will facilitate your email workflow.

django-anymail


This is a collection of email backends and webhooks for numerous famous email services including SendGrid, Mailgun, and others. django-anymail works with the django.core.mail module and normalizes the functionality of transactional email service providers. 

django-mailer


django-mailer is a Django app you can use to queue email sending. With it, scheduling your emails is much easier. 

django-post_office


With this app, you can send and manage your emails. django-post_office offers many cool features like asynchronous email sending, built-in scheduling, multiprocessing, etc.

django-templated-email


This app is about sending templated emails. In addition to its own functionalities, django-templated-email can be used in tow with django-anymail to integrate transactional email service providers.

How to receive emails in Django


To receive emails in Django, it is better to use the django-mailbox development library if you need to import messages from local mailboxes, POP3, IMAP, or directly receive messages from Postfix or Exim4.

While using Django-mailbox, mailbox functions as a message queue that is being gradually processed. The library helps retrieve email messages and then erases them so they are not downloaded again the next time.

Mailbox types supported by django-mailbox: POP3, IMAP, Gmail IMAP with Oauth2 authentication, local file-based mailboxes like Maildir, Mbox, Babyl, MH, or MMDF.

Here’s a step-by-step guide on how to quickly set up your Django-mailbox and start receiving emails.

Installation


There are two ways to install django-mailbox:

1. From pip:

pip install django-mailbox

2. From the github-repository:

git clone https://github.com/coddingtonbear/django-mailbox.git
cd django-mailbox
python setup.py install
  • After installing the package, go to settings.py file of the django project and add django_mailbox to INSTALLED_APPS.
  • Then, run python manage.py migrate django_mailbox from your project file to create the necessary database tables.
  • Finally, go to your project’s Django Admin and create a mailbox to consume.
  • Don’t forget to verify if your mailbox was set up right. You can do that from a shell opened to your project’s directory, using the getmail command running python manage.py getmail

When you are done with the installation and checking the configurations, it’s time to receive incoming emails. There are five different ways to do that.

  1. In your code

Use the get_new_mail method to collect new messages from the server.

  1. With Django Admin

Go to Django Admin, then to ‘Mailboxes’ page, check all the mailboxes you need to receive emails from. At the top of the list with mailboxes, choose the action selector ‘Get new mail’ and click ‘Go’.

  1. With cron job

Run the management command getmail in python manage.py getmail

  1. Directly from Exim4

To configure Exim4 to receive incoming mail begin with adding a new router:

django_mailbox: debug_print = 'R: django_mailbox for $localpart@$domain' driver = accept transport = send_to_django_mailbox domains = mydomain.com local_parts = emailusernameone : emailusernametwo

In case the email addresses you are trying to add are handled by other routers, disable them. For this change, the contents of local_parts must match a colon-delimited list of usernames for which you would like to receive mail.

5. Directly from Postfix

With Postfix get new mail to a script using pipe. The steps to set up receiving incoming mail directly from Postfix are pretty much the same as with Exim4. However, you might need to check out the Postfix pipe documentation

There’s also an option to subscribe to the incoming django-mailbox signal if you need to process your incoming mail at the time that suits you best.

Use this piece of code to do that:

from django_mailbox.signals import message_received
from django.dispatch import receiver @receiver(message_received)
def dance_jig(sender, message, **args): print "I just received a message titled %s from a mailbox named %s" % (message.subject, message.mailbox.name, )

Keep in mind that this should be loaded to models.py or elsewhere early enough for the signal not to be fired before your signal handler’s registration is processed.


We hope that you find our guide helpful and the list of packages covered help facilitate your email workflow. You can always find more apps at Django Packages.

? This article was originally published on Mailtrap’s blog: Sending emails in Django with code examples. We have repurposed it on the Finxter blog with their permission! ?



https://www.sickgaming.net/blog/2022/09/...in-django/

Print this item

  (Indie Deal) FREE AVA: Dark History, Capcom & Star Wars Deals
Posted by: xSicKxBot - 09-28-2022, 12:27 PM - Forum: Deals or Specials - No Replies

FREE AVA: Dark History, Capcom & Star Wars Deals

VA: Dark History FREEbie
[freebies.indiegala.com]
Mysterious, dark as night, hard as a saw platformer. AVA: Dark story in the world "Koutei"

https://www.youtube.com/watch?v=voDMl86jK7k
Capcom, Star Wars, GameMill Sales
[www.indiegala.com]
https://www.youtube.com/watch?v=huaus9oy6xM


https://steamcommunity.com/groups/indieg...2818051680

Print this item

 
Latest Threads
௹©Ukraine Shein COUPON Co...
Last Post: udwivedi923
4 hours ago
௹©Morocco Shein COUPON Co...
Last Post: udwivedi923
4 hours ago
௹©USA Shein COUPON Code ...
Last Post: udwivedi923
4 hours ago
௹©Armenia Shein COUPON Co...
Last Post: udwivedi923
5 hours ago
௹©Brazil Shein COUPON Cod...
Last Post: udwivedi923
5 hours ago
௹©South Africa Shein COUP...
Last Post: udwivedi923
5 hours ago
௹©Moldova Shein COUPON Co...
Last Post: udwivedi923
5 hours ago
௹©Malta Shein COUPON Code...
Last Post: udwivedi923
5 hours ago
௹©Luxembourg Shein COUPON...
Last Post: udwivedi923
5 hours ago
௹©Kazakhstan Shein COUPON...
Last Post: udwivedi923
5 hours ago

Forum software by © MyBB Theme © iAndrew 2016